problem dynamically removing items from a droplist..?

M

Milsnips

hi there,

i have the following HTML code:
--------------------------
<asp:DropDownList id="hddList" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3">Item 3</asp:ListItem>
<asp:ListItem Value="4">Item 4</asp:ListItem>
<asp:ListItem Value="5">Item 5</asp:ListItem>
<asp:ListItem Value="6">Item </asp:ListItem>
</asp:DropDownList>
--------------------------

and the following VB.NET code behind:
----------------------------------
Private Sub hddList_PreRender(ByVal sender As Object, ByVal e As
System.EventArgs) Handles hddList.PreRender
If hddList.Items.Count > 0 Then
If Request.QueryString("type") <> "" Then
For Each i As ListItem In hddList.Items
If i.Value <> Request.QueryString("type") Then
'remove item not to be shown
hddList.Items.Remove(i.Text)
End If
Next
End If
End If
End Sub
----------------------------------

What i am doing is if querystring value = , say 3, i want to programatically
remove all items and only leave Value=3 in there but i am getting an error:

Exception Details: System.InvalidOperationException: Collection was
modified; enumeration operation may not execute.

please help,
Paul
 
K

Kevin Spencer

You're using an enumerator, which iterates from item number 1 to item number
last, but you're removing each item as you move forward through the
Collection. This makes the enumerator unable to correctly iterate through
the list, as the size of it has changed. For future reference, if you ever
need to loop through a Collection to find something, start at the end. But
in this case, you don't need any such thing. The DropDownList Items property
is a List ItemCollection, which has a FindByText and FindByValue method,
which you can use without any looping. Example:

If Request.QueryString("type") <> "" Then
Dim li As ListItem =
hddList.Items.FindByValue(Request.QueryString("type"))
If Not IsNothing(li) Then
hddList.Items.Remove(li)
End If
End If

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
To a tea you esteem
a hurting back as a wallet.
 
M

Milsnips

thanks Kevin,

i'll try that.. although i want kinda the opposite of what u showed me.. i
want to remove all items that dont equal the querystring("type") - is it
possible this way, or would i need to do something else?

thanks,
Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,056
Messages
2,570,441
Members
47,119
Latest member
NoeliaIrby

Latest Threads

Top