Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ObservableCollection to DataGridView

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();
        }
    }
}
like image 324
Belmiris Avatar asked Aug 18 '12 03:08

Belmiris


1 Answers

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

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

like image 182
Binary Worrier Avatar answered Nov 01 '22 11:11

Binary Worrier