Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move selected items from one listbox to another in C# winform

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);
}
like image 243
user1770370 Avatar asked Nov 12 '12 13:11

user1770370


1 Answers

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

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.

full source:

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);
}

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

like image 182
Habib Zare Avatar answered Sep 20 '22 06:09

Habib Zare