Solved

move items from one listbox to another

Posted on 2016-09-21
2
39 Views
Last Modified: 2016-09-21
Hi,

The following is my code, I am trying to move items from one listbox to another. But I am getting

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

I guess it is because as item in listBox1 was removed, the count is different.

    protected void MoveMultibtn_Click(object sender, EventArgs e)
    {

        if (listBox1.SelectedIndex == -1)
        {
            testBox.Text = "Please select an item";
        }
        else
        {
                foreach (ListItem item in listBox1.Items)
                {
                    if (item.Selected)
                    {
                        listBox2.Items.Add(item);
                        listBox1.Items.Remove(listBox1.SelectedItem);
                    }
                }


        }



    }

Open in new window

0
Comment
Question by:mcrmg
2 Comments
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 41809431
When enumerating a list to remove items, you have to do it in reverse.  This means that you do one of two things:

A.  Use a reversed for...loop:
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
	if ((listBox1.Items[i] as ListItem).Selected)
	{
		listBox2.Items.Add(listBox1.Items[i]);
		listBox1.Items.Remove(listBox1.Items[i]);
	}
}

Open in new window

B.  Use a reversed foreach...loop:
foreach (var item in listBox1.Items.Cast<ListItem>().Reverse())
{
	if (item.Selected)
	{
		listBox2.Items.Add(item);
		listBox1.Items.Remove(item);
	}
}

Open in new window


-saige-
0
 

Author Closing Comment

by:mcrmg
ID: 41809509
thank you very much
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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…

713 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