How to remove multiple selected items in ListBox?(如何删除列表框中的多个选定项?)
问题描述
我的窗体包含两个列表框.Listbox1 中包含一些项目,而 listbox2 为空.当我按下表单上的按钮时,应将 listbox1 中的多个选定项目从 Listbox1 中删除并复制到 Listbox2.
My windows form contains two listboxes. Listbox1 contains some items in it and listbox2 is empty. When I press a button on the form, then multiple selected items from listbox1 should be removed from Listbox1 and copied to Listbox2.
我在 listbox1.SelectedItems 上尝试了 foreach 循环,但它只从列表中删除了一项.
I tried with foreach loop on listbox1.SelectedItems but it removes only 1 item from list.
有人有解决方案或代码吗?
Anyone has solution or code for this?
推荐答案
您可以在一个循环中完成所有操作.您应该在 SelectedIndices 上使用简单的 for 并向后循环:
You could do all in a single loop. You should use a simple for and loop backwards on SelectedIndices:
private void button1_Click(object sender, EventArgs e)
{
for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox2.Items.Add(listBox1.Items[idx]);
listBox1.Items.RemoveAt(idx);
}
}
这篇关于如何删除列表框中的多个选定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除列表框中的多个选定项?
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
