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
2009-09-11 07:58:22
i want to remove more than two items
2009-09-11 08:01:50
i have tried this option. wher removing the second item it shows the error System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
2009-09-11 09:00:48
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
2009-09-11 20:59:16
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
2009-12-30 17:12:51