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:
The following will remove nothing:
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 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.
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.
Post a Comment