8

I am binding an observable collection (FoodList) to a BindingSource in my WinForm. This BindingSource is used by a datagrid on the form. I had assumed that when I added a new item to the collection it would raise an event and a new row would show up in my grid. This does not happen though.

namespace Foods
{
    public class FoodList : ObservableCollection<Food>
    {

    }
}

private void frmFoods_Load(object sender, EventArgs e)
{
    try
    {
        foodSource = new Source("Foods.xml");
        foodBindingSource.DataSource = foodSource.Foods;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void AddFood()
{
    using (frmFood frm = new frmFood())
    {
        frm.ShowDialog(this);
        if (!frm.Canceled)
        {
            foodSource.Foods.Add(frm.Food);     // <-- No new row.
            //foodBindingSource.ResetBindings(false);
            foodDataGridView.ClearSelection();
            foodDataGridView.CurrentCell = foodDataGridView[0, foodDataGridView.Rows.Count - 1];
            foodDataGridView.Focus();
        }
    }
}
Belmiris
  • 2,741
  • 3
  • 25
  • 29
  • I added a listener to the form for the foodSource.Foods observable collection and it DID fire an add event. Maybe the DataGridView in WinForms does not support ObservableCollections? I know MS is really pushing WPF, maybe this is a WPF only feature? – Belmiris Aug 18 '12 at 04:06
  • 9
    See [this](http://stackoverflow.com/questions/1723041/a-good-collection-to-use-when-binding-to-a-datagridview-in-c-sharp).ObservableCollection won't work for a DataGridView : it implements INotifyCollectionChanged, not IBindingList, and the DataGridView doesn't know about INotifyCollectionChanged. It is intended for WPF bindings and is not used in Windows Forms. – Jacob Seleznev Aug 18 '12 at 13:54

1 Answers1

17

ObservableCollection<T> doesn't work with WinForms controls.

However BindingList<T> will work the way you expect.

Binary Worrier
  • 50,774
  • 20
  • 136
  • 184