在 C# winform 中将所选项目从一个列表框移动到另一个列表框 [英] Move selected items from one listbox to another in C# winform

查看:30
本文介绍了在 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 中将所选项目从一个列表框移动到另一个列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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