C# – Binding ObservableCollection to DataGridView

cdatagridviewwinforms

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

Best Answer

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

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

Related Topic