Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing DataGridView columns based on the grid width

I'm having a windows form. In this form I've datagrid control which has few columns with predefined width.

When I resize the form either by using maximize box or using mouse, datagrid automatically resizes itself to fit the form. This is done using anchor property of the datagrid.

Now I need to resize the width of the columns as well so that all the columns fit within resized grid without getting horizontal scroll bar. At present I'm doing this by calculating the ratio of the new grid width with the old grid width and increasing the column width in the same ratio. But the problem in this is the ratio is not accurate when I maximize and minimize the form, so after couple of resize actions total columns width is less than the grid width and it starts showing empty space in the grid. I'm doing this in grid resize event.

Another catch in this is, there are couple of fixed columns also present in this grid and I'm not supposed to change the width of those columns on grid resize.

How should we handle this? Is there any other way to handle this resize problem?

Update: I was doing unnecessary job of calculating the ratio to increase the width of the columns, which is not necessary.

Thanks @KMan. Your suggestion to use the fill property worked. It takes care of column width resizing based on the grid changed width on form resize.

like image 890
JPReddy Avatar asked Sep 29 '10 09:09

JPReddy


1 Answers

How about:

  • You set the AutoSizeColumnsMode property to AllCellsExceptHeader, this would adjust all columns according to the values.

  • And, to your last column, you can set the style to Fill.

Also, checkout How to: Set the Sizing Modes of the Windows Forms DataGridView Control.

like image 149
KMån Avatar answered Nov 15 '22 06:11

KMån