Tuesday, April 19, 2005

Remove ListItems, by value, from the DropDownList

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/remove_listitems_by_value_from_the_dropdownlist.htm]

There are times when you'll want to add a set of items to a DropDownList, and then remove certain items. For example, you may databind a code-value table from a shared database, but then need to exclude potential values based on individual configuration settings.

The DropDownList.Items property is a ListItemCollection that supports the Remove and RemoveAt methods. The RemoveAt simply takes an index (of type integer) and removes the item at that specific index. However, referencing items by index can be delicate. For example, if the DropDownList added a blank space at the top to indicate that the field was optional, that would bump all the indexes off by one. For lookup dropdowns, where the text is a description and the value is a unique primary key, we'd like to be able to remove items by value.

The problem is that the Remove(string) method is based on a "string representation" of the list item, NOT just the value. So if we add items to a dropdown like so:

this.DropDownList1.Items.Add(new ListItem("Apple","101"));
this.DropDownList1.Items.Add(new ListItem("Banana","201"));
this.DropDownList1.Items.Add(new ListItem("Orange","301"));
this.DropDownList1.Items.Add(new ListItem("Mango"));

 The following will remove nothing:

this.DropDownList1.Items.Remove("Banana");    //Text
this.DropDownList1.Items.Remove("201");    //Value

Remove(string) works by first constructing a new ListItem from that string, and then removing that ListItem. In other words, Remove works acts like so:

this.DropDownList1.Items.Remove(new ListItem("Banana"));


This will create a new ListItem with both the text and description being the same ("201"). Therefore if the list items have different text and values, which they almost always do, then the Remove(string) method by itself won't work.

However, we can make our own method that cycles through the dropdown and removes if the value matches. Note that we could make this more reusable by sending in the dropdown as a ref parameter.

public static void RemoveByValue(ref DropDownList d, string strKey)
{
    for (int i = 0; i < d.Items.Count; i++)
    {       
        if (d.Items[i].Value == strKey)
        {
            d.Items.RemoveAt(i);
            return;
        }
    }
}

Given that dropdowns are only intended for small sets of data, cycling through all the items isn't a significant performance hit.

This provides a reusable method to remove items (by value) from a dropdown list.

No comments:

Post a Comment