C# WinForms DataSource Property Errors

78 views Asked by At

Currently using Winforms and trying to edit items in a listbox to move up and down and i've followed a few guides on here and i keep getting an error 'items collection cannot be modified when the DataSource property is set.'

This is my code.

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



    }


}

}

1

There are 1 answers

1
John Wu On BEST ANSWER

You can't remove or add items while the control is bound to a data source.

For your purposes, perhaps you should avoid using DataBind completely, and instead just copy the data like this:

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