Slow to set DataGridView DataSource to DataTable in C#

梦想与她 提交于 2019-12-06 02:52:09

Check the formatting options, especially the Fill -related properties. Adjusting columnwidths for all rows involves a lot of calculation.

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

With this code I have good results:

dtgvPlanificado.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
dtgvPlanificado.ColumnHeadersVisible = False  
dtgvPlanificado.DataSource = DS.Tables("LV1")  
dtgvPlanificado.ColumnHeadersVisible = True  
dtgvPlanificado.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

AutoSizeColumnsMode is the real bottleneck ... and 11 seconds become 15 ms.

Here is what I was looking for:

<System.Runtime.CompilerServices.Extension()>
Public Sub BeginLoadData(dataGridView As DataGridView)
    dataGridView.Tag = dataGridView.AutoSizeColumnsMode
    dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
End Sub

<System.Runtime.CompilerServices.Extension()>
Public Sub EndLoadData(dataGridView As DataGridView)
    dataGridView.AutoSizeColumnsMode = CType(dataGridView.Tag, DataGridViewAutoSizeColumnsMode)
End Sub

for me changing RowHeadersWidthSizeMode from:

DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

to:

DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;

was extremely helpfull.

Don't forget that the autosize rows can also play a role. This works well for me. Took the databinding from ~1 sec to 0.1 sec. I wish everything was that easy to get a 10x speed up!

dgvProperties.DataSource = Nothing
dgvProperties.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
dgvProperties.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
dgvProperties.DataSource = datatable
dgvProperties.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
dgvProperties.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!