在 C# winform 中将所选项目从一个列表框移动到另一个列表框

Move selected items from one listbox to another in C# winform(在 C# winform 中将所选项目从一个列表框移动到另一个列表框)
本文介绍了在 C# winform 中将所选项目从一个列表框移动到另一个列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表框 1 中的选定项目移动到列表框 2,反之亦然.我有两个按钮,>><<.当我选择 listbox1 中的项目然后单击 >> 时,项目应该从 listbox1 移动到 listbox2.

I'm trying to move selected items in list box1 to list box2, and vice versa. I have two buttons, >> and <<. When I select items in listbox1 and then click on >> the items should move from listbox1 to listbox2.

private void MoveListBoxItems(ListBox source, ListBox destination)
{
    ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
    foreach (var item in sourceItems)
    {
        destination.Items.Add(item);
    }
    while (source.SelectedItems.Count > 0)
    {
        source.Items.Remove(source.SelectedItems[0]);
    }
}

private void button2_Click_1(object sender, EventArgs e)
{
    MoveListBoxItems(listbox , lstActivity);
}

推荐答案

您的代码运行良好.我测试了它.您的问题是我尝试将列表框 1 中的 选定 项移动到列表框 2."

your code works fine. i tested it. your question is "I try to move selected item in list box1 to list box2."

我认为你的 button2 有问题.删除 button2 和下面的代码

i think your button2 has problem.delete button2 and the code below

private void button2_Click_1(object sender, EventArgs e)
{
    MoveListBoxItems(listbox , lstActivity);
}

然后创建其他按钮并创建点击事件.

then create other button and create click event.

完整来源:

private void MoveListBoxItems(ListBox source, ListBox destination)
{
    ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
    foreach (var item in sourceItems)
    {
        destination.Items.Add(item);
    }
    while (source.SelectedItems.Count > 0)
    {
        source.Items.Remove(source.SelectedItems[0]);
    }
}

private void first2second_Click(object sender, EventArgs e)
{
    MoveListBoxItems(FirstListbox, LastListbox);
}

private void second2first_Click(object sender, EventArgs e)
{
    MoveListBoxItems(LastListbox, FirstListbox);
}

此代码有效.如果要选择多个项目更改属性SelectionMode = MultiSimple;

this code is work. if you want select more than one item change property SelectionMode = MultiSimple;

这篇关于在 C# winform 中将所选项目从一个列表框移动到另一个列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)