C# DataGridView AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells

吃可爱长大的小学妹 提交于 2020-01-14 10:48:26

问题


I am displaying a table with up to 100,000 rows in a DataGridView. The table has one column which contains large strings. I found out that setting AutosizeMode to AllCells causes the application to freeze for a long time while its computing the required width. As a compromise, I set the Autosize mode to DisplayedCells. I then bound a method to the dataGrid's scroll event:

public void MethodThatBindsDataToTheDatagridview(DataTable table)
{
   dataGrid.Source = table;
   dataGrid.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
   dataGrid.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
}

public void DataGridScroll(object sender, ScrollEventArgs e)
{
   ((DataGridView)sender).Update();
}

I also tried the same with Refresh method. My expectation is that the DataGrid will set the columns width according to the displayed rows. However, this happens only once when the table is loaded, but the scroll event does not trigger a change in the columns width.


回答1:


Calling the AutoResizeColumn method on the datagridview is what you need to do:

 dataGrid.AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.DisplayedCells);
 dataGrid.AutoResizeColumn(2, DataGridViewAutoSizeColumnMode.DisplayedCells);



回答2:


You could also use the method AutoResizeColumns(DataGridViewAutoSizeColumnsMode autoSizeColumnsMode), provided that all of your columns should be resized using the same algorithm. That way, your code also apply to any columns you may add in the future.

Surprisingly, the overload AutoResizeColumns() will resize all columns using the setting AllCells, rather than resize each column according to its AutoSizeMode setting.



来源:https://stackoverflow.com/questions/4827426/c-sharp-datagridview-autosizemode-datagridviewautosizecolumnmode-displayedcell

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