transfer items from one listbox to another

僤鯓⒐⒋嵵緔 提交于 2020-01-15 23:44:07

问题


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
    {

    }

回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/19576802/transfer-items-from-one-listbox-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!