Search code examples
c#.netdatagridview

DataGridView column auto adjust width and resizable


I am wondering if it is possible to have a dataGridView column to adjust automatically its width to its content and at the same time being resizable by the user ?

Here what i have tried so far :

dataGridView.AllowUserToResizeColumns = true;
dataGridView.Columns[0].AutoSizeMode=DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridView.Columns[0].Resizable = DataGridViewTriState.True;

But, I am still unable to resize the column size manually.

If anyone already faced this issue or have any idea let me know.

Thanks.


Solution

  • 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.