Search code examples
winformsdatagridviewautosize

C# DataGridView AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells


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.


Solution

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

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