Removing list items from the DropDownList

2019-03-25 00:47发布

问题:

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.

回答1:

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
}


回答2:

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


回答3:

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.



回答4:

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.