Wednesday, June 6, 2007

Browsers Back button capability in ASP.Net forms

Today I ran into a problem of creating a back button capability to one of my ASP.Net form and as usual as every newbie programmer I searched for code snippets,solutions over google. I did find some reference to this issue and the code cited did not meet my requirement COMPLETELY and I had to figure it out myself.Heres what I came up with

I have a server control Button on my form and on click I wanted to go back to the page from where the request came.

private static string previousPageURL = String.Empty;

protected void Page_Load(object sender,EventArgs e)
{
if(!IsPostback)
previousPageURL = this.Request.Urireferer.AbsoluteUri;

}
protected void BackButton_Click(object sender,EventArgs e)
{
Response.Redirect(previousPageURL);
}

The issue was that without the static keyword the string variable previousPageURL was being initialized to "" eventhough during the first page load it got the right URL of the previous page.
Using Hyperlinks or Linkbutton would have been a better choice since the NavigateUrl property could be automatically assigned the URL when the page first loads.If you use a button and if the suggested method in the various articles,blogs does not work check whether the variable's value is being overwritten.

Hope it helps.

Monday, June 4, 2007

Enumerating SQL Instances in a local network

When I started working on a versioning tool for SQL server databases, I wanted to list all the SQL server instances in the local network. After much searching and testing, I came up with this code snippet below. Apparently the .Net framework already has a class that can do the job for you. There are various ways on doing these and if you search with the title of the blog on google you will definitly get quite a few.I will keep it simple and small.For more information search on the classname SqlDataSourceEnumerator in msdn.


try
{
SqlDataSourceEnumerator Sqlen = SqlDataSourceEnumerator.Instance;
DataTable dt = Sqlen.GetDataSources();
foreach (DataRow row in dt.Rows)
{
ServercomboBox.Items.Add(row[0]);
}
}
catch
{
MessageBox.Show("Server lists could not be loaded");
}

Hope that helps