C# – Threadsafe Updating of DataGridView / Dataset When DataGridView is Editable

cdatagridviewdatasetmultithreading

I have a WinForms application that contains a Dataset ds and a DataGridView dgv. dgv is bound to ds.

ds is updated via a Task() that periodically queries a database using the TableAdapter.Fill() method. There are two issues that I am experiencing here.

  1. When ds is updated, dgv is not refreshed unless a the window is resized or some other event causes a redraw of the form.

  2. When a user begins to edit a cell in dgv, ds is updated and causes a UI crash due to multiple threads accessing the same GUI control. I have attempted using a flag, EditModeOn, which is set by certain events from DataGridView dgv, though this has not helped in preventing the thread errors.

What is the best way to have a DataGridView that can be edited by a user and is updated via changes to the bound dataset (which is updated in another thread)?

Best Answer

For your point #2, you can use the function Invoke from the Control class. This function will execute the function in the UI Thread.

http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx

Ex. :

// Invoke an anonymous method on the thread of the form.
this.Invoke((MethodInvoker) delegate
{
    //Call your function to update your datagridview with the dataset in parameters
    ...
});
Related Topic