Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to refresh datagridview when updating data source?


Asked by Haven Ferguson on Dec 02, 2021 FAQ



I've got something like this (and it works), but setting the DataGridView.DataSource to null doesn't seem like the right way.
Besides,
It's got nothing specifically to do with the DataGridView class. Update and Refresh are methods of the Control class, so all controls have those methods. To understand what they do, you need to throw the Invalidate method and Paint event into the mix as well. With GDI+ in Windows Forms, controls are getting repainted on screen quite often.
In respect to this, The problem here is that your dataset is disconnected from the database, so your datagrid is updating correctly, but the dataset is not changed. You could use SQL changenotification events (google it) but this requires changes in the SQL server setup.
Additionally,
The Invalidate method tells the control what area or areas it needs to repaint. If you call Invalidate with no parameters then the entire control surface will be repainted on the next Paint event.
Moreover,
The BindingList has events that fire when items are added or changed, and the DataGridView will automatically update itself when these events are fired. Well, it doesn't get much better than that.