【问题标题】:Moving item from one list box to another list box (c# webforms)将项目从一个列表框移动到另一个列表框(c# webforms)
【发布时间】:2012-07-02 20:30:04
【问题描述】:

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

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 事件不能。列表框没有数据绑定,我已经手动向它们添加了项目。

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

提前感谢您的帮助。

【问题讨论】:

    标签: c# listbox


    【解决方案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。另外,我想如果选择了多个项目,您的代码将不起作用。

    【讨论】:

    • NominSim 还发现了另一个错误,如果您选择了超过 1 个项目,这将不起作用。
    【解决方案2】:

    更改您的 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;
    }
    

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

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

    【讨论】:

    • 感谢 Nominsim 的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多