Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow to set DataGridView DataSource to DataTable in C#

I have a DataTable, fully populated, which I want to set to a DatagridView:

gdv.DataSource = dt;

However, this is painfully slow. The filling of the DataTable is very quick, but just this one line above takes ages. Is there any way to speed this up or perform it in another thread?

There is no interaction after this point. Just the simple statement above!

Thanks.

like image 243
Mark Avatar asked Dec 06 '22 00:12

Mark


2 Answers

Check the formatting options, especially the Fill -related properties. Those are AutoSizeColumnMode and the individual column styles.

Adjusting columnwidths for all rows involves a lot of calculation.

like image 91
Henk Holterman Avatar answered Dec 24 '22 11:12

Henk Holterman


Here is a fix. The problem is that the framework re-resizes the columns once per row in the new datasource (why??). And of course it needs to loop over all rows each time, resulting in an O(n^2) operation. So sadly it looks like you must turn off autoresize before setting the datasource, then manually call the AutoResizeColumns method.

grdChanges.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
grdChanges.DataSource = schemaChangesSpreadsheet.Changes
grdChanges.AutoResizeColumns(DataGridViewAutoSizeColumnMode.AllCells)

Turns out that Microsoft tells you to do this in an article "Best Practices for Scaling the Windows Forms DataGridView Control" which might help you if you have a different UI setting that has the same heavy computation issue.

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

like image 35
AndyClaw Avatar answered Dec 24 '22 10:12

AndyClaw