Monday, December 21, 2009

Select by text in a Dropdown List

In case if you have a senario where you need to load the dropdownlist with the data from the datasource . When the dropdownlist is loaded you need to select the selected value to a user which he previously selected. For example
if you have a dropdownlist that displays all States. But, in your database the user already have selected a state from the dropdownlist. Now when you load this dropdownlist again, you want to have the selected State as the first value in the dropdownlist. You can do so by the following methods.


public void SelectByText(DropDownList list, string text)
{
ListItem ItemToFind = list.Items.FindByValue(text);
if (ItemToFind != null)
{
if (list.Items.Contains(ItemToFind))
{
list.SelectedValue = ItemToFind.Value;
}
}
}

where the parameter in the method "Dropdownlist list" is your dropdownlist and "string text" represents the State which the user has already selected.

Another Method

You can also use the below code.

ddl.SelectedValue = Convert.ToString(ddl.Items.FindByText("AA").Value);

.