简体   繁体   English

C#多选列表框移动

[英]C# multiple selection listbox move

What I have is two listboxs. 我有两个列表框。

In listbox1 I want the user to be able to click a button and move all selected items to listbox two. 在listbox1中,我希望用户能够单击按钮并将所有选定项目移动到列表框2。 Also if there is nothing selected i dont want the button to work. 此外,如果没有选择,我不希望按钮工作。 Anybody have any suggestions? 有人有什么建议吗?

listbox1.items.add(listbox2.selecteditems); listbox1.items.add(listbox2.selecteditems); just moves over (collection) to the 2nd listbox. 只是移动(集合)到第二个列表框。

I guess you will need to move the items separately: 我想你需要分开移动物品:

List<object> itemsToRemove = new List<object>();

foreach (var item in listbox2.SelectedItems)
{
    listbox1.Items.Add(item);
    itemsToRemove.Add(item);
}

foreach (var item in itemsToRemove)
{
    listbox2.Items.Remove(item);
}

This will move any selected items from listbox2 to listbox1 . 这会将listbox2 listbox1所有选定项目移动到listbox1 The itemsToRemove list is used as a temporary storage since you cannot modify a collection while iterating over it; itemsToRemove列表用作临时存储,因为在迭代时无法修改集合; while iterating we just add references to the items to be removed into a temporary list, then we iterate over that list and remove the items. 迭代时我们只是将要删除的项的引用添加到临时列表中,然后我们遍历该列表并删除项。

In order to handle the case when no items are selected, I would set up an event handler for the SelectedIndexChanged event, and set the Enabled property of the button: 为了处理没有选择项目的情况,我将为SelectedIndexChanged事件设置一个事件处理程序,并设置按钮的Enabled属性:

theButton.Enabled = (listbox2.SelectedItems.Count > 0);

Here's a solution using Linq: 这是使用Linq的解决方案:

private void buttonMove_Click(object sender, EventArgs e)
{
    foreach (var item in listBox1.SelectedItems.OfType<object>().ToArray())
    {
        listBox1.Items.Remove(item);
        listBox2.Items.Add(item);
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    buttonMove.Enabled = listBox1.SelectedItems.Count > 0;
}

for Winforms: 对于Winforms:

foreach (var i in listbox1.SelectedItems) {
     listbox2.SelectedItems.add(i);
}

To enable the button only when necessary add code to the OnSelectionChanged event and set button1.enabled = (Listbox1.SelectedItems.Count > 0); 仅在必要时启用按钮,将代码添加到OnSelectionChanged事件并设置button1.enabled = (Listbox1.SelectedItems.Count > 0);

if (listbox1.SelectedItems.Count == 0)
{
    return;
}

// Do this if you want to clear the second ListBox
listbox2.Items.Clear();

foreach (object obj in listbox1.SelectedItems)
{
    listbox2.Items.Add(obj);
}

For Listbox1 use the SelectedItemChanged Event and use your EventArgs provided to get the selected item -> then add to listbox2. 对于Listbox1,使用SelectedItemChanged事件并使用提供的EventArgs获取所选项目 - >然后添加到listbox2。

If no item is selected button.enbabled = false; 如果没有选择项目button.enbabled = false;

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

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