How to: Set the selected item in a web list control
This is certainly not brain surgery (or rocket science), but I needed some code as an example for my CSS overrides to add code in my blog. These overrides rely on code being copied using the CopySourceAsHTML add-in. So there you go.
When you want to set the selected item in a DropDownList, you will find the index for the item you wish to select. This is pretty straight forward using the FindUsingValue (or FindUsingText) and the IndexOf methods. But you will need to handle situations where items just don't exist. So for my current web application I created a small method to do this. It's probably useless, but I like it:
/// Sets the selected item in the drop down list to the specified value in a
/// safe manner. When no matching item could be found, the methed will select
/// the first item in the list.
/// <param name="listControl">The list control in which to select the value.</param>
/// <param name="value">The value to select in the items list</param>
public static void SetSelectedItem(ListControl listControl, string value)
if (listControl == null) throw new ArgumentNullException("listControl");
if (listControl.Items.Count == 0) throw new ArgumentOutOfRangeException("listControl", "The list must contain items.");
// Get the currently selected item, or the first item in the list
// when no item was selected.
ListItem selectedItem = (listControl.SelectedItem != null ? listControl.SelectedItem : listControl.Items);
// Try to find the item for the specified value doesn't match the value
// for the current selected item.
// A value is specified, so try to find it.
if ((value != null) && (value.Length > 0))
ListItem valueItem = listControl.Items.FindByValue(value);
if (valueItem != null)
// Deselect the current item and assign the new value item
// as the selected item.
selectedItem.Selected = false;
selectedItem = valueItem;
// Set the selected item
selectedItem.Selected = true;