How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

This trick works for me:

    grd.DataSource = DT;

    // Set your desired AutoSize Mode:
    grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

    // Now that DataGridView has calculated it's Widths; we can now store each column Width values.
    for (int i = 0; i <= grd.Columns.Count - 1; i++)
    {
        // Store Auto Sized Widths:
        int colw = grd.Columns[i].Width;

        // Remove AutoSizing:
        grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

        // Set Width to calculated AutoSize value:
        grd.Columns[i].Width = colw;
    }

In the Code above: You set the Columns AutoSize Property to whathever AutoSizeMode you need. Then (Column by Column) you store each column Width value (from AutoSize value); Disable the AutoSize Property and finally, set the Column Width to the Width value you previously stored.


Maybe you could call

dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);

After setting datasource. It will set the width and allow resize.

More on MSDN DataGridView.AutoResizeColumns Method (DataGridViewAutoSizeColumnsMode).


A C# version of Miroslav Zadravec's code

for (int i = 0; i < dataGridView1.Columns.Count-1; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int colw = dataGridView1.Columns[i].Width;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dataGridView1.Columns[i].Width = colw;
}

Posted as Community Wiki so as to not mooch off of the reputation of others