Tuesday, February 6, 2007

Set Selected DropDownList Item By Value

Given an ASP.NET DropDownList control and a value, you can set the selected item in that list if the value exists. There are a couple of ways to do this, but this approach takes into consideration that the value may not be found in the list.

This is an example of what you could have on an ASPX page:
<asp:DropDownList ID="ddlDb" runat="server">
<asp:ListItem Value="all" Selected="True">All</asp:ListItem>
<asp:ListItem Value="opt1">Option One</asp:ListItem>
<asp:ListItem Value="opt2">Option Two</asp:ListItem>
This is an example of how to set the selected item:
ListItem li = ddlDb.Items.FindByValue("opt1");
if (li != null) ddlDb.SelectedIndex = ddlDb.Items.IndexOf(li);
Another method is below, but it will throw System.ArgumentOutOfRangeException if the value is not found:
ddlDb.SelectedValue = "opt1";


saifur said...

hi m saif ur rehman, working as systems analyst, i was tired and at the same time i was facing a problem, for the dropdown selected value and ur sugession help me to remove this bug from the applicaitons, thanks


Dinesh Kumar said...

"78") != null)
// Note: The above condition works for both the values
// 1) NULL 2) and even if the value is not found in the dropdownlist