DataGridView bound to BindingList does not refresh when value changed

后端 未结 5 412
独厮守ぢ
独厮守ぢ 2020-12-05 07:47

I have a DataGridView bound to a BindingList (C# Windows Forms). If I change one of the values in an item in the list it does not immediately show up in the grid. If I click

相关标签:
5条回答
  • 2020-12-05 08:26

    It sounds as your Change Object notification is not triggered / handled correctly. I personally always use the BindingSource object when binding to a dataGridView.

    I would check out the DataGridView FAQ and the DataBinding FAQ and search for object change notification.

    If you are using ADO.Net, don't forget the call the .Validate() and .EndEdit() methods.

    0 讨论(0)
  • 2020-12-05 08:27

    ListChanged notifications for item value changes are only raised if the list item type implements the INotifyPropertyChanged interface.

    Taken from: http://msdn.microsoft.com/en-us/library/ms132742.aspx

    So my first question would be: Implements your item the INotifyPropertyChanged properly?

    0 讨论(0)
  • 2020-12-05 08:31
        private void refreshDataGrid()
        {
            dataGridView1.DataSource = typeof(List<>);
            dataGridView1.DataSource = myBindingList;
            dataGridView1.AutoResizeColumns();
            dataGridView1.Refresh();
        }
    

    Then, just call for the refreshDataGrid Method anytime a change occurs to your list.

    0 讨论(0)
  • 2020-12-05 08:34

    Your datasource should implement INotifyPropertyChanged for any change in the BindingList to be reflected in the 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> books= new BindingList<Books>();
    
    datagridView.DataSource = books;
    
    0 讨论(0)
  • 2020-12-05 08:37

    Just call myBindingList.ResetBindings() whenever your data changes!

    0 讨论(0)
提交回复
热议问题