DataGridView doesn't update changed cells automatically.

S

Sin Jeong-hun

Hi.
Thank you for your answers as always. Today, I have encountered a
problem with DataGridView. I have bound a DataGridView to a list of my
objects. It displayed them all right, but when I have changed the
value of an object in the list, the DataGridView didn't instantly
reflected the change on its display. Only after when I resize the form
or minimise then maximise (that is, make the form redrawn), it updates
the display. It seems to have a manual update method like
UpdateCellValue, but I don't think this is a good approach. Maybe I'm
missing a good practice. Instead of directly changing the value of the
underlying datasource object, should I use some other way to change it?
 
K

kndg

Hi Sim,

If you need two-way notification, use BindingList<T> instead.
Your object also need to implement the INotifyPropertyChanged interface.
For example,

public class CustomObject : INotifyPropertyChanged
{
private string data;

public event PropertyChangedEventHandler PropertyChanged;

public string Data
{
get { return data; }
set
{
data = value;
OnPropertyChanged("Data");
}
}

private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null )
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

On your MainForm declare your list as below,

BindingList<CustomObject> list = new BindingList<CustomObject>();


Then, set the DataSource of your DataGridView to the BindingList object,

dataGridView1.DataSource = list;


Regards,
 
R

RealCat

Thank you. I'll try it.

Hi Sim,

If you need two-way notification, use BindingList<T> instead.
Your object also need to implement the INotifyPropertyChanged interface.
For example,

public class CustomObject : INotifyPropertyChanged
{
   private string data;

   public event PropertyChangedEventHandler PropertyChanged;

   public string Data
   {
     get { return data; }
     set
     {
       data = value;
       OnPropertyChanged("Data");
     }
   }

   private void OnPropertyChanged(string propertyName)
   {
     if (PropertyChanged != null )
     {
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
   }

}

On your MainForm declare your list as below,

BindingList<CustomObject> list = new BindingList<CustomObject>();

Then, set the DataSource of your DataGridView to the BindingList object,

dataGridView1.DataSource = list;

Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top