You need to use the DataGridViewColumn.AutoSizeMode property.
You can use one of these values ββfor columns 0 and 1:
AllCells: The column width is adjusted to match the contents of all cells in the column, including the header cell.
AllCellsExceptHeader: The column width is adjusted to match the contents of all cells in the column, excluding the header cell.
DisplayedCells: The column width is adjusted to match the contents of all the cells in the column that are currently in the rows displayed on the screen, including the header cell.
DisplayedCellsExceptHeader: The column width is adjusted to match the contents of all the cells in the column that are currently in the rows displayed on the screen, excluding the header cell.
Then you use the Fill value for column 2
The column width is adjusted so that the width of all columns exactly fills the display area of ββthe control ...
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
As other users note, the default value can be set at the datagridview level using the DataGridView.AutoSizeColumnsMode property.
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
may be:
this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
Important Note:
If your grid is bound to a data source and the columns are automatically generated ( AutoGenerateColumns property set to True), you need to use the DataBindingComplete event to apply AFTER style columns.
In some scenarios (for example, changing a cell value by code) I had to call DataGridView1.AutoResizeColumns(); to refresh the grid.
Chris Sep 06 '13 at 21:27 2013-09-06 21:27
source share