Friday, April 11, 2008

C# DataGridView and Multithreading Problem

I had some problems updating datagridview from another thread. Problem is in painting scrollbars (vertical one). One thing that is interesting is that everything is working fine if you start your program from VisualStudio debugger.

My first solution to this problem was: I've disabled scrollbars and application works fine.

After some time of research I've found solution to my problem!!!

to simplify there is two posibilities:

1. you have datagridview without binded datasource
Solution: use delegate to add rows, or update existing.

2. you have datagridview with binded datasource (for example datatable)
Solution: use delegate to update datatable/datasource,

if you dont now how, you can start from this article.


keys: c# datagridview multithread freeze, scrollbar problem, c# application freeze, program hangup, multithread gui update, datagridview update from another thread, threading, csharp.

3 comments:

Yusuf Avcı said...

Hello Niko,

we have datagridview with binded datasource which is datatable? Datatable updates very rapidly with port messages. Then datagridview refresh automaticaly but sometimes it freezes. Can you give me an example how to use delegate to update datatable? we are in trouble, waiting your helps thank you...

M.I. said...

This works only if you update your datatable from thread another that created datagridview.

delegate void updateDataTableDelegate(DataTable dt [row, objects or whatever]);

private void updateDataTable(DataTable dt)
{
if (dataGridView1.InvokeRequired)
{
updateDataTableDelegate del = new updateDataTableDelegate(updateDataTable);
dataGridView1.Invoke(del, new object[] { dt });
} else {
yourDataTable.Merge(dt);
}
}

Anonymous said...

C# build DataGridView in Windows Forms