C# WinForms 数据源 属性 错误

C# WinForms DataSource Property Errors

目前正在使用 Winforms 并尝试编辑列表框中的项目以上下移动,我已经遵循了此处的一些指南,但我不断收到错误消息 'items collection cannot be modified when the DataSource property is set.'

这是我的代码。

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {

        //Add button was clicked

        x = x + 1;

        _items.Add("New item " + x);

        //Change the data source
        listBox1.DataSource = null;
        listBox1.DataSource = _items;

    }

    private void button3_Click(object sender, EventArgs e)
    {

        //The remove button
        int selectedIndex = listBox1.SelectedIndex;

        try
        {

            //Removes the item in the list
            _items.RemoveAt(selectedIndex);
            x = x - 1;

        }

        catch
        {
        }

        listBox1.DataSource = null;
        listBox1.DataSource = _items;

    }

    private void button4_Click(object sender, EventArgs e)
    {

        x = 0;

        _items.Clear();

        listBox1.DataSource = null;
        listBox1.DataSource = _items;

    }

    private void button5_Click(object sender, EventArgs e)
    {

        MoveUp();

    }

    private void button6_Click(object sender, EventArgs e)
    {

        MoveDown();

    }

    public void MoveUp()
    {

        MoveItem(-1);

    }

    public void MoveDown()
    {

        MoveItem(1);

    }

    public void MoveItem(int direction)
    {

        //Checking selected item
        if (listBox1.SelectedItem == null || listBox1.SelectedIndex < 0)
            return;//No selected item, nothing will happen

        //Calculating new index using move direction
        int newIndex = listBox1.SelectedIndex + direction;

        //Checking bounds of th range
        if (newIndex < 0 || newIndex >= listBox1.Items.Count)
            return; //Index out of range - nothing will happen

        object selected = listBox1.SelectedItem;

        //Removing removable element
        listBox1.Items.Remove(selected);
        //Insert it into new position
        listBox1.Items.Insert(newIndex, selected);
        //restore selection
        listBox1.SetSelected(newIndex, true);



    }


}

}

当控件绑定到数据源时,您不能删除或添加项目。

出于您的目的,也许您应该完全避免使用 DataBind,而是像这样复制数据:

foreach (var item in _items)
{
    myListBox.Items.Add(item);
}