Click here to Skip to main content
15,913,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a list box there is 5 data.i want to remove data from listbox but when i am clik on botton
then getting error
Collection was modified; enumeration operation may not execute.

my Coding is
C#
foreach (ListItem selectItem in lstSelectPages.Items)
{
    if (selectItem.Selected == true)
    {
        lstSelectPages.Items.Remove(lstSelectPages.SelectedItem);
        lstSelectPages.DataBind();      
    }
}

please help me out
Posted
Updated 18-Aug-21 3:41am
v3

Foreach does not allow the manupulation of the collection. Try for loop as shown.


C#
for(int x=0; x < lstSelectPages.Items.Count;x++)
            {
                if (lstSelectPages.SelectedItem == lstSelectPages.Items[x])
                {
                    lstSelectPages.Items.RemoveAt(x);
                    lstSelectPages.DataBind();
                }
            }
 
Share this answer
 
Comments
Pradhan Gagan 10-Aug-13 3:48am    
THANKS LOT I GOT RAGING SOLUTION FROM ONLY YOUR SIDE
ArunRajendra 10-Aug-13 4:56am    
Can you mark the solution as answered. :)
ArunRajendra 10-Aug-13 4:55am    
welcome :)
The loop is not needed at all:
SQL
if (lstSelectPages.SelectedItem != null)
{
    lstSelectPages.Items.Remove(lstSelectPages.SelectedItem);
    lstSelectPages.DataBind();
}
 
Share this answer
 
Comments
Maciej Los 12-Aug-13 4:35am    
+5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900