Solved

Removing value from Listbox gives exception

Posted on 2007-11-22
11
407 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
 
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now