Haider Khattak
Haider Khattak

Reputation: 577

transfer items from one listbox to another

so far i have accomplished transfer a single select item from one lb1 to lb2 and vice versa. Now the problem is transfering the whole list of data from lb1 to lb2 and vice versa. if anyone could help please. using for loop will be much better.

i am using the following code:

    private void add_Click(object sender, EventArgs e)
    {
        if (lb1.SelectedItem != null)
        {
            lb2.Items.Add(lb1.SelectedItem);
            lb1.Items.Remove(lb1.SelectedItem);
        }
        else
        {
            MessageBox.Show("No item selected");
        }
    }

    private void remove_Click(object sender, EventArgs e)
    {
        if (lb2.SelectedItem != null)
        {
            lb1.Items.Add(lb2.SelectedItem);
            lb2.Items.Remove(lb2.SelectedItem);
        }
        else
        {
            MessageBox.Show("No item selected");
        }
    }

    private void addall_Click(object sender, EventArgs e) //problem is here. adding all the items from lb1 to lb2
    {
        for (int i = 0; i < lb1.SelectedItems.Count; i++)
        {
            lB2.Items.Add(lb1.SelectedItems[i].ToString());
        }
    }

    private void removeall_Click(object sender, EventArgs e) //problem is here. adding all the items from lb2 to lb1
    {

    }

Upvotes: 1

Views: 24714

Answers (3)

User 12345678
User 12345678

Reputation: 7804

Because you want to transfer all of the items from one list box to another not only the selected items you must loop for every item in the list box and not only the selected items.

So change your usage of ListBox.SelectedItems to ListBox.Items and your code should work as expected assuming you remember to remove the items as well.

for (int i = 0; i < lb1.Items.Count; i++)
{
    lB2.Items.Add(lb1.Items[i].ToString());
}
lb1.Items.Clear();

Upvotes: 3

Philip W
Philip W

Reputation: 791

Simply iterate over all Items of the list and add each element to the next list. At the end simply remove all Items.

foreach (var item in listBox1.Items)
{
    listBox2.Items.Add(item);
}
listBox1.Items.Clear();

Upvotes: 0

PiousVenom
PiousVenom

Reputation: 6908

You could do something like this:

private void addall_Click(object sender, EventArgs e)
{
    foreach (var item in lb1.Items)
    {
        lB2.Items.Add(item);
    }
}

This would loop through your list and add them all. You would do the reverse for lb2->lb1.

Upvotes: 1

Related Questions