DataGridView - how to set column width?
Solution 1:
You can use the DataGridViewColumn.Width
property to do it:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx
Solution 2:
The following also can be tried:
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
or use the other setting options in the DataGridViewAutoSizeColumnsMode Enum
Solution 3:
Most of the above solutions assume that the parent DateGridView
has .AutoSizeMode
not equal to Fill
. If you set the .AutoSizeMode
for the grid to be Fill
, you need to set the AutoSizeMode for each column to be None
if you want to fix a particular column width (and let the other columns Fill). I found a weird MS exception regarding a null object if you change a Column Width and the .AutoSizeMode
is not None
first.
This works
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
This throws a null exception regarding some internal object regarding setting border thickness.
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
// chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
Solution 4:
I know this is an old question but no one ever answered the first part, to set width in percent. That can easily be done with FillWeight (MSDN). In case anyone else searching comes across this answer.
You can set DataGridAutoSizeColumnMode to Fill in the designer. By default that gives each column FillWeight of 100. Then in code behind, on FormLoad event or after binding data to grid, you can simply:
gridName.Columns[0].FillWeight = 200;
gridName.Columns[1].FillWeight = 50;
And so on, for whatever proportional weight you want. If you want to do every single column with numbers that add up to 100, for a literal percent width, you can do that too.
It gives a nice full DataGrid where the headers use the whole space, even if the user resizes the window. Looks good on widescreen, 4:3, whatever.