Search code examples
c#winformsbindingsource

How do I update underlying list when calling BindingSource.RemoveCurrent


I have the following simple class;

public class MyObject
{
    public int Id {get;set;}
    public string Name {get;set;}
}

List<MyObject> oList = new List<MyObject>();

My list is populated with some items. I then populate my BindingSource with the list like;

MyBindingSource.DataSource = oList; //contains some items in a list

My BindingSource is linked to a DataGridView (which doesn't really matter in this example), but depending on the selected row in the DataGridView, I then have the following method for my datagrid view clicked button;

private void MyDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == btnRemove.Index)
    {
        MyBindingSource.RemoveCurrent();
    }
}

The call

MyBindingSource.RemoveCurrent()

removes the items from the DataGridView, but how do I remove the item from the underlying list which is oList.

I thought that assigning MyBindingSource.DataSource = oList, means the list shown in MyBindingSource.DataSource is actually pointing to oList ?


Solution

  • List<T> isn't smart enough to know things have changed, so try using a BindingList<T> from System.ComponentModel instead:

    BindingList<MyObject> oList = new BindingList<MyObject>();