2
votes

I have one DataGridView and whose Dock property is set to "Fill". So when I resize my form then DataGridViewwill resize. In my case, I set DataGridViewcolumn width with a fixed value. Like so:

dgGrid.Columns[0].Width = 50;
dgGrid.Columns[1].Width = 126;
dgGrid.Columns[2].Width = 100;

I am trying to the columns in my DataGridView to resize proportionally when the control is resized. How can I do it programatically when my grid column with is set like above? Please help me with code.Thanks.

3
You seem to manage to use capital letters when writing code. Why not when writing English? - Cody Gray
Setting the width in percentage would be the solution. To bad WinForms don't support this. Considering switching to WPF instead of the now obsolete WinForms. - Claus Jørgensen
@Claus: I'm not sure why "switch to WPF" has become the answer whenever someone doesn't know how to implement something in WPF. Switching to WPF is certainly not a miracle cure. In particular, where do you find a DataGridView control for a WPF application without embedding the WinForms one? - Cody Gray
<DataGrid /> (that was hard, huh :p) - Claus Jørgensen

3 Answers

2
votes

There's no particularly elegant way of doing this when you hard-code the column width values. I'm not sure why you have to do that in the first place; the question doesn't give much background information.

The better solution is to call the AutoResizeColumns method, which will automatically adjust the width of all your columns using the specified size mode. You would call this method in the handler for your form's Resize event. For example:

protected override void OnResize(EventArgs e)
{
    myDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}

This MSDN article gives more information about sizing options for the DataGridView control.

1
votes

You can use DataGridView.Resize event to canlculate new width for every column depending on new size of

0
votes
datagridview.Columns["columnName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;