1

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
    {

    }
4

3 回答 3

3

因为您希望将所有项目从一个列表框中传输到另一个列表框中,不仅是所选项目,您必须为列表框中的每个项目循环,而不仅仅是所选项目。

因此,如果您还记得删除这些项目,那么更改您对ListBox.SelectedItemsto的使用,ListBox.Items您的代码应该可以按预期工作。

for (int i = 0; i < lb1.Items.Count; i++)
{
    lB2.Items.Add(lb1.Items[i].ToString());
}
lb1.Items.Clear();
于 2013-10-24T21:19:58.807 回答
1

你可以这样做:

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

这将遍历您的列表并将它们全部添加。你会做相反的事情lb2->lb1

于 2013-10-24T21:20:49.737 回答
0

只需遍历列表的所有项目并将每个元素添加到下一个列表。最后只需删除所有项目。

foreach (var item in listBox1.Items)
{
    listBox2.Items.Add(item);
}
listBox1.Items.Clear();
于 2013-10-24T21:24:23.123 回答