views:

575

answers:

3

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  A: 

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
}
Canavar
i want to remove more than two items
i have tried this option. wher removing the second item it shows the error System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
A: 

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
Jason Berkan
A: 

hi this is not good answer for drop downlist

can you suggest me for this question

how i can remove the multiple value from dropdownlist.

vipul