如何从多个列表框中删除所选项目

时间:2011-08-16 10:39:16

标签: c#

我有两个列表框,listbox1选择了索引已更改事件的代码为:

      listBox2.SelectedIndex = listBox1.SelectedIndex

所以当我点击一个列表框中的项目时,在另一个列表框中自动选择具有相同索引的项目,现在我想用一个按钮删除这两个项目。当我写下面的代码时:

      listBox1.Items.Remove(listBox1.SelectedItem);
      listBox2.Items.Remove(listBox2.SelectedItem);

它只删除Listbox1 SelectedItem,为什么不删除ListBox 2 selectedItem? 我需要紧急的帮助/回复。我会非常感激/感谢你们所有人。 感谢,

2 个答案:

答案 0 :(得分:3)

尝试以其他顺序删除它们:

  listBox2.Items.Remove(listBox2.SelectedItem);
  listBox1.Items.Remove(listBox1.SelectedItem);

当您在第一个ListBox中删除了selecteditem时,SelectionChanged正在触发并将listbox2的SelectedItem设置为null。

答案 1 :(得分:0)

另一个解决方案是将每个列表框的选定索引保存在两个单独的变量中,然后通过预先存储的索引删除每个项目。

相关问题