简体   繁体   English

无法将列表框的选定项目传输到另一个列表框

[英]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; System.InvalidOperationException:集合已修改; 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 .) (另外,我认为您的意思是li ,不是liNew 。)


Without LINQ, it might look like: 没有LINQ,它可能看起来像:

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: 另外,可以使用@Steve建议的for循环:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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