C # DataGridView AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells

I am showing a table with up to 100,000 rows in a DataGridView. The table has one column that contains large rows. I found out that setting AutosizeMode to "AllCells" causes the application to freeze for a long time while calculating the required width. As a compromise, I set Autosize mode to DisplayedCells. Then I attached the method to the dataGrid scroll event:

public void MethodThatBindsDataToTheDatagridview(DataTable table) { dataGrid.Source = table; dataGrid.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; dataGrid.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; } pubic void DataGridScroll(object sender, ScrollEventArgs e) { ((DataGridView)sender).Update(); } 

I also tried the same with the Refresh method. I expect the DataGrid to set the width of the columns according to the rows displayed. However, this only happens once when the table is loaded, but the scroll event does not cause the column width to change.

+4
source share
2 answers

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

  dataGrid.AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.DisplayedCells); dataGrid.AutoResizeColumn(2, DataGridViewAutoSizeColumnMode.DisplayedCells); 
+5
source

You can also use the AutoResizeColumns method (DataGridViewAutoSizeColumnsMode autoSizeColumnsMode) , provided that all your columns must be changed using the same algorithm. Thus, your code also applies to any columns that you may add in the future.

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

0
source

Source: https://habr.com/ru/post/1337455/


All Articles