DataGridView column auto adjust width and resizable

I finally find a way to do what I wanted.

The idea is to

  • let the dataGridView resize the columns itself to fit the content, and then
  • change theAutoSizeColumnMode and set the width with the value you just stored.

Here is the code:

dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
int widthCol = dataGridView.Columns[i].Width;
dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridView.Columns[i].Width = widthCol;

Hope this will help.