Solved

Removing value from Listbox gives exception

Posted on 2007-11-22
11
415 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
  • 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
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 …

786 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