Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I automatically size columns in a DataGrid so they fill the grid's client area?

If you add a DataGridTableStyle to your DataGrid, then you can use the ColWidth property of the GridColumnStyles to set the width of each column. To dynamically set these widths as the grid is resized, you can handle the SizeChanged event of the DataGrid. In your handler, you can compute the width of each column by dividing the client width minus the width of the row header column by the number of columns. Now there are a couple of technical points. You have to adjust for a possible vertical scrollbar. And, you have to adjust things for possible integer rounding in the calculations. To handle this last problem, the attached samples (both VB and C#) apply the single computed width to all but the last column. And this last column is just given all the space left. This means the last column may differ in width from the other columns by a couple of pixels.

Contributed from George Shepherd's Windows Forms FAQ



Page view counter