2008/09/21

Set the value of a DropDownList control by a given text or value

Usually we will set the default of a DropDownList control by using this command:

ddlCompany.SelectedIndex = 1;
However, what should we do if we only have a text string or a value of that text? For example, I want to bind this table to a DropDownList control:
ID  Name
--  -----
1   HP
2   IBM
3   Microsoft

And we want dynamically set the default value when the QueryString is presented, like http://xxxxxx/company.aspx?ID=2 or http://xxxxxx/company.aspx?Name=IBM.  In this scenario, we have to use the following codes to set the default value of the DropDownList control:

foreach (ListItem li in ddlCompany.Items)
{
if (li.Value == "2")
{
li.Selected = true;
break;
}
}
or

foreach (ListItem li in ddlCompany.Items)
{
if (li.Text == "IBM")
{
li.Selected = true;
break;
}
}

No comments:

Post a Comment