Solved

Removing value from Listbox gives exception

Posted on 2007-11-22
11
421 Views
Last Modified: 2008-02-01
Hi,

I am working on C# using ASP.net 2.0

I have Listbox, There I have a button to add the values It works fine.

Also there is button to remove the selected values.

When I use my below code, It gives me error saying

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code

Additional information: Collection was modified; enumeration operation may not execute.


toplevel: Exception of type 'System.Web.HttpUnhandledException' was thrown.

inner: Collection was modified; enumeration operation may not execute.


Code on Remove button click is:

foreach (ListItem lstItm in List_Options.Items)
{
      if (lstItm.Selected)
      {
          List_Options.Items.Remove(lstItm);
      }
}

ASPX listbox
<asp:ListBox ID="List_Options" runat="server" Rows="6" SelectionMode="Multiple"></asp:ListBox>


Thanks
0
Comment
Question by:tia_kamakshi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 20333991
you can remove only one item then you need to come oput ofr for loop

foreach (ListItem lstItm in List_Options.Items)
{
      if (lstItm.Selected)
      {
          List_Options.Items.Remove(lstItm);
          break;
      }
}
0
 
LVL 7

Expert Comment

by:lucky_james
ID: 20334001
lstItm.Selected may not be enough to check. if there is no item in the listbox then the seleceted index would be -1. i think it would be better if you change it as following :

foreach (ListItem lstItm in List_Options.Items)
{
      if ((lstItm.Selected) && (List_Options.Count > 0))
      {
          List_Options.Items.Remove(lstItm);
      }
}

Open in new window

0
 
LVL 7

Expert Comment

by:lucky_james
ID: 20334009
plz put a break after
          List_Options.Items.Remove(lstItm);
as you did in your code. :)
0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 20334012
You can try like this

You can store the selected indexes in array

then

For( i=0; i<arr.Lenght; i++)
{
List_Options.Items.RemoveAt(arr(i));
}
0
 

Author Comment

by:tia_kamakshi
ID: 20334056
Hi,


Thanks for your replies,

I tried. Here it says that ListBox does not contain the defination of Count

Also I am getting the error at line

foreach (ListItem lstItm in List_Options.Items)
In this case I can never reach to the line

if ((lstItm.Selected) && (List_Options.Count > 0))

foreach (ListItem lstItm in List_Options.Items)
{
      if ((lstItm.Selected) && (List_Options.Count > 0))
      {
          List_Options.Items.Remove(lstItm);
      }
}
           
           
pratima_mcs:

Thank you as well. Can you please help me more on your solution

How to implement?

For( i=0; i<arr.Lenght; i++)
{
List_Options.Items.RemoveAt(arr(i));
}

Thanks
0
 
LVL 19

Expert Comment

by:Limbeck
ID: 20334112
hi,l try this:
    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < List_Options.Items.Count; i++)
        {
            if (List_Options.Items[i].Selected == true)
            {
                List_Options.Items.RemoveAt(i);
            }
        }
    }
}

Open in new window

0
 
LVL 7

Expert Comment

by:bungHoc
ID: 20334120
I think you should change to loop backwards.

Reason: everytime you remove an item from your ListBox the total number will be changed and therefore the index will also be affected.

for (int i = List_Options.Items.Count; i > 0; i--)
{
  List_Options.Items.RemoveAt(i);
}
0
 
LVL 7

Accepted Solution

by:
bungHoc earned 250 total points
ID: 20334141
This works fine:
for (int i = List_Options.Items.Count - 1; i >= 0; i--)
{
  if (List_Options.Items[i].Selected)
 {
    List_Options.Items.Remove(lbxSelectedLocations.Items[i]);
  }
}
 
//Or
 
while (List_Options.SelectedItems.Count > 0)
{
  List_Options.Items.Remove(List_Options.SelectedItems[0]);
}

Open in new window

0
 
LVL 5

Expert Comment

by:gocemi
ID: 20334159
This will do the job:

int j = ListBox.Items,Count;
for(int i=0; i < j ; i++)
{
if (List_Options.Items[i].Selected == true)
            {
                List_Options.Items.RemoveAt(i);
             j = j-1;
             i - i-1;
            }

}
0
 
LVL 7

Expert Comment

by:lucky_james
ID: 20334160
yeah, the count you can find in listboxobj.items.Count
0
 

Author Comment

by:tia_kamakshi
ID: 20334572
Limbeck:
In your solution, It is only deleting 1 selected value, If we select multiple than it is not deleting all

Anyway, thanks  to all for the solution

Cheers
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

742 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question