Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

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:

/// <summary>
/// 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.
/// </summary>
/// <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[0]);
 
    // Try to find the item for the specified value doesn't match the value
    // for the current selected item.
    if (!selectedItem.Value.Equals(value)) 
    {
        // 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;
}

 

Comments

oruga said:

very good
# May 10, 2006 3:05 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 8 and 8 and type the answer here: