绑定到BindingList的DataGridView在值更改时不会刷新

我有一个绑定到BindingList(C#Windows窗体)的DataGridView。 如果我更改列表中某个项目中的某个值,则不会立即显示在网格中。 如果我点击更改的单元格,或最小化然后最大化它正确更新的窗口,但我需要它自动发生。

我之前遇到过同样的问题,但在那种情况下,我必须在值改变的同时更改单元格的背景颜色。 这导致单元格正确刷新。

我能让它发挥作用的唯一方法是……

dataGridView.DataSource = null; dataGridView.DataSource = myBindingList 

…但我真的想避免这种情况,因为它会使滚动条弹回到顶部,这意味着我必须再次设置我的单元格背景颜色。 当然有更好的方法。 我尝试过刷新(以及刷新父级),更新和无效,但他们没有做我需要的事情。

我已经在一些留言板上看到了这个问题,但还没有看到它的工作答案。

仅当列表项类型实现INotifyPropertyChanged接口时,才会引发项值更改的ListChanged通知。

摘自: http : //msdn.microsoft.com/en-us/library/ms132742.aspx

所以我的第一个问题是:正确实现你的项目INotifyPropertyChanged

您的数据源应实现INotifyPropertyChanged以便BindingList中的任何更改都反映在datagridview中。

 class Books : INotifyPropertyChanged { private int m_id; private string m_author; private string m_title; public int ID { get { return m_id; } set { m_id = value; NotifyPropertyChanged("ID"); } } public string Author { get { return m_author; } set { m_author = value; NotifyPropertyChanged("Author"); } } public string Title { get { return m_title; } set { m_title = value; NotifyPropertyChanged("Title"); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string p) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(p)); } } BindingList books= new BindingList(); datagridView.DataSource = books; 

只要数据发生变化,就调用myBindingList.ResetBindings()

听起来,您的更改对象通知未被正确触发/处理。 我个人总是在绑定到dataGridView时使用BindingSource对象。

我将查看DataGridView FAQ和DataBinding FAQ并搜索对象更改通知。

如果您使用的是ADO.Net,请不要忘记调用.Validate()和.EndEdit()方法。

  private void refreshDataGrid() { dataGridView1.DataSource = typeof(List<>); dataGridView1.DataSource = myBindingList; dataGridView1.AutoResizeColumns(); dataGridView1.Refresh(); } 

然后,只要在列表发生更改时调用refreshDataGrid方法。