简体   繁体   中英

Unable to transfer Selected Items of a ListBox to another ListBox

I am unable to transfer the Selected Items from one ListBox to another ListBox:

 protected void Button2_Click(object sender, EventArgs e)
    {
        foreach (ListItem li in ListBox2.Items)
        {
            if (li.Selected)
            {
                ListItem liNew = new ListItem(li.Text, li.Value);                
                ListBox1.Items.Add(liNew);
                ListBox2.Items.Remove(liNew);
            }
        }
    }

I am getting the exception:

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

The problem is that you can't remove elements from a collection while you're iterating it. Instead, you can select the items that are selected :) and loop over them.

foreach(ListItem li in ListBox2.Items.Where(x => x.Selected)) {
    ListItem liNew = new ListItem(li.Text, li.Value);
    ListBox1.Items.Add(liNew);
    ListBox2.Items.Remove(li);
}

(Also, I think you meant li , not liNew .)


Without LINQ, it might look like:

List<ListItem> toRemove = new List<ListItem>();

foreach(ListItem li in ListBox2.Items) {
    if(li.Selected) {
        ListItem liNew = new ListItem(li.Text, li.Value);
        ListBox1.Items.Add(liNew);
        toRemove.Add(li);
    }
}

foreach(ListItem li in toRemove) {
    ListBox2.Items.Remove(li);
}

Also, you can use a for loop, as suggested by @Steve:

for(int i = ListBox2.Items.Count; --i >= 0;) {
    ListItem li = ListBox2.Items[i];

    if(li.Selected) {
        ListItem liNew = new ListItem(li.Text, li.Value);
        ListBox1.Items.Add(liNew);
        ListBox2.Items.RemoveAt(i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM