I am wondering if it is possible to have a dataGridView column to adjust automatically its width to its content and at the same time being resizable by the user ?
Here what i have tried so far :
dataGridView.AllowUserToResizeColumns = true;
dataGridView.Columns[0].AutoSizeMode=DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridView.Columns[0].Resizable = DataGridViewTriState.True;
But, I am still unable to resize the column size manually.
If anyone already faced this issue or have any idea let me know.
Thanks.
To adjust column widths programmatically, use the AutoResizeColumn or AutoResizeColumns methods or set the column Width property. For more information about content-based automatic sizing, see Sizing Options in the Windows Forms DataGridView Control.
Users can make size adjustments by dragging or double-clicking row, column, or header dividers. In column fill mode, column widths change when the control width changes; for example, when the control is docked to its parent form and the user resizes the form.
To set column width dynamically In code, set the Width property of the ItemStyle property for a GridView control column to the width that you want.
The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor.
I finally find a way to do what I wanted.
The idea is to
dataGridView
resize the columns itself to fit the content, and thenAutoSizeColumnMode
and set the width with the value you just stored.Here is the code:
dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
int widthCol = dataGridView.Columns[i].Width;
dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridView.Columns[i].Width = widthCol;
Hope this will help.
Building on the code above to iterate it for all columns and also auto adjust the width of the DataGridView
//initiate a counter
int totalWidth = 0;
//Auto Resize the columns to fit the data
foreach (DataGridViewColumn column in mydataGridView.Columns)
{
mydataGridView.Columns[column.Index].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
int widthCol = mydataGridView.Columns[column.Index].Width;
mydataGridView.Columns[column.Index].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
mydataGridView.Columns[column.Index].Width = widthCol;
totalWidth = totalWidth + widthCol;
}
//the selector on the left of the DataGridView is about 45 in width
mydataGridView.Width = totalWidth + 45;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With