如何删除列表框中的多个选定项? [英] How to remove multiple selected items in ListBox?

查看:20
本文介绍了如何删除列表框中的多个选定项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的窗体包含两个列表框.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);
    } 
} 

这篇关于如何删除列表框中的多个选定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆