Question

I have a dropdownlist inside a gridview, that is loaded from a datasource when the gridview loads. Could someone please show me how I go about looping the dropdownlist and removing certain items from the list based on a if condition.

Was it helpful?

Solution

No need to loop the items, just find the item and remove it :

ListItem itemToRemove = myDropDown.Items.FindByValue("value");
if (itemToRemove != null)
{
    myDropDown.Items.Remove(itemToRemove);
}

Or if you know the index of the item to remove, use RemoveAt method :

myDropDown.Items.RemoveAt(0);

But if you want to loop anyway, here is the loop :

foreach (ListItem item in myDropDown.Items)
{
    // your stuff
}

OTHER TIPS

You cannot use foreach to remove items, as once you have removed an item, the collection is modified, and the loop throws an exception.

If you must loop through the collection to remove multiple items, the best solution is to loop backwards through the collection. My C# is pretty rusty, so the following is in VB. Should be easy to convert.

For x As Integer = myDropDown.Items.Count - 1 to 0 Step -1
    Dim item As ListItem = myDropDown.Items(x)
    If item.TestToSeeIfItShouldBeRemoved = True
        myDropDown.Items.RemoveAt(x)
    End If
End For

You can not use a for-each loop because you can not modify the collection while using the enumerator object. The best way to do it is to count backwards as stated by @Jason. Or use a for loop like this:

for (int i = 0; i < this.MyDropDownList.Items.Count; i++)
{
    //test to see if this item needs to be removed or not
    if (IsToBeRemoved(this.MyDropDownList.Items[i]))
    {
        this.MyDropDownList.Items.Remove(this.MyDropDownList.Items[i]);
        //re-set to next item in the list (count changed after item removed)
        i -= 1;
    }
}

Just note that after you remove the ListItem, the DropDownList item count will change. So you will need to decrement your counter variable i, or else you risk not evaluating all the items.

Why can't you use for each item in mycollection.ToList() This way you can make changes during the iteration through your list, since the collection is converted to a copy of a list and not the actual list itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top