Binding ObservableCollection to DataGridView

依然范特西╮ 提交于 2021-02-07 03:16:38

问题


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

回答1:


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

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



来源:https://stackoverflow.com/questions/12015576/binding-observablecollection-to-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!