0

我遇到了一个奇怪的问题,我可以将项目从一个列表框移动到另一个列表框,但不能将任何项目移回原始列表框。这是我的代码:

private void MoveListBoxItems(ListBox from, ListBox to)
{
    for(int i = 0; i < first_listbox.Items.Count; i++)
    {
        if (first_listbox.Items[i].Selected)
        {
            to.Items.Add(from.SelectedItem);
            from.Items.Remove(from.SelectedItem);
        }   
    }
    from.SelectedIndex = -1;
    to.SelectedIndex = -1;
}

protected void Button2_Click(object sender, EventArgs e)
{
    MoveListBoxItems(first_listbox, second_listbox);
}

protected void Button1_Click(object sender, EventArgs e)
{
    MoveListBoxItems(second_listbox, first_listbox); 
}

button2 事件可以正常工作,但是 button1 事件不能。列表框没有数据绑定,我已经手动向它们添加了项目。

也许我在这里遗漏了一些非常明显的东西?

提前感谢您的帮助。

4

2 回答 2

1

将其更改为:

private void MoveListBoxItems(ListBox from, ListBox to)
{
    for(int i = 0; i < from.Items.Count; i++)
    {
        if (from.Items[i].Selected)
        {
            to.Items.Add(from.SelectedItem);
            from.Items.Remove(from.SelectedItem);

            // should probably be this:
            to.Items.Add(from.Items[i]);
            from.Items.Remove(from.Items[i]);
        }   
    }
    from.SelectedIndex = -1;
    to.SelectedIndex = -1;
}

您原来的方法是first_listbox在这两个地方使用,而不是from. 另外,我想如果选择了多个项目,您的代码将不起作用。

于 2012-07-02T20:32:56.443 回答
1

更改您的 for 循环以迭代本地参数from,而不是特别是first_listbox

private void MoveListControlItems(ListControl from, ListControl to)
{
    for(int i = 0; i < from.Items.Count; i++)
    {
        if (from.Items[i].Selected)
        {
            to.Items.Add(from.Items[i]);
            from.Items.Remove(from.Items[i]);
        }   
    }
    from.SelectedIndex = -1;
    to.SelectedIndex = -1;
}

如果要一次移动多个项目,还需要切换添加和删除。

只是另一个想法,虽然这主要是个人喜好,但如果您将参数类型切换为,您也可以对'sListControl使用相同的方法。ComboBox

于 2012-07-02T20:33:56.013 回答