How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?
Solution 1:
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.
Solution 2:
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).
Solution 3:
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
Solution 4:
In my application I have set
grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
Also, I have set the
grid.AllowUserToOrderColumns = true;
grid.AllowUserToResizeColumns = true;
Now the column widths can be changed and the columns can be rearranged by the user. That works pretty well for me.
Maybe that will work for you.
Solution 5:
After adding the data to the grid add the following code which will adjust the column according to the length of data in each cell
dataGrid1.AutoResizeColumns();
dataGrid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
Here is the Result