I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).
My goal is to display a grid that neatly fills all available width with cells - i.e. no un
dataGridView1.AutoResizeColumns();
Resume of the question:
Have column width adapt to the content (with different method across the column),
but then allow the user to set the column width...
Developing from Miroslav Zadravec's answer, for me what worked was immediately using the auto computed column.Width
to set... column.Width
!
foreach (DataGridViewColumn column in dataGridView.Columns)
{
if (/*It's not your special column*/)
{
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
column.Width = column.Width; //This is important, otherwise the following line will nullify your previous command
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
}
}
//Now do the same using Fill instead of AllCells for your special column
This is tested to work when the DataGridView
is already created, using a trick like this.
If I understood the question correctly there should be an easier way to accomplish what you need. Call
dgvSomeDataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
That should do the trick. However, there is one pitfall as you cannot simply call this method directly after populating your DataGridView control. Instead you will have to add an EventHandler for the VisibleChanged event and call the method in there.
A simple two lines of code works for me.
dataGridView.DataSource = dataTable;
dataGridView.AutoResizeColumns();
You could do something like this:
grd.DataSource = getDataSource();
if (grd.ColumnCount > 1)
{
for (int i = 0; i < grd.ColumnCount-1; i++)
grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[grd.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
if (grd.ColumnCount==1)
grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
All columns will adapt to the content except the last one will fill the grid.
Well, I did this like this:
dgvReport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dgvReport.AutoResizeColumns();
dgvReport.AllowUserToResizeColumns = true;
dgvReport.AllowUserToOrderColumns = true;
in that particular order. Columns are resized (extended) AND the user can resize columns afterwards.