Code:
public static void SetValue(this DropDownList control, string value) { // variables var ListItem = control.Items.Cast<ListItem>().Where(x => x.Value.IsEqual(value)).FirstOrDefault(); // check for match if (ListItem != null) { control.ClearSelection(); ListItem.Selected = true; } }
Example usage:
ddlState.SetValue(State);
Dependencies:
The SetValue extension method is dependent on the IsEqual extension method previously discussed.
This same technique can also be applied to the HtmlSelect control.
public static void SetValue(this HtmlSelect control, string value) { // variables var ListItem = control.Items.Cast<ListItem>().Where(x => x.Value.IsEqual(value)).FirstOrDefault(); // check for match if (ListItem != null) { ListItem.Selected = true; } }
0 comments: