Sunday 10 October 2010

Asp.Net: Initialize DropDown from Url Query Parametes

Question:
How do I initialize my drop down lists with query parameters?




Answer:
In the onLoad event you fill you list and then you set the selected value as shown below.
This will do nothing if the value is not found. You do not want to throw an exception just because the user played with the url :)

Here is an example
if (this.Page.Request.QueryString.AllKeys.Contains("myParam"))
{
    string val = this.Page.Request.QueryString["myParam"];
    ListItem item = myDropDown.Items.FindByValue(val);
    if (item != null)
    {
        item.Selected = true;
    }
}

2 comments:

Anonymous said...

An exception will be throwned if another item in the list is already set as "selected"...
That's why I prefer to use the list's SelectedIndex property.

jens said...

interesting point. Didn't test the case you mention.