问题
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