Implement responsive columns in a WinForms data grid
The latest version of the FlexGrid control for WinForms adds a powerful and convenient feature that has been available in other versions of the FlexGrid for quite a while: star-sizing. Star-sizing allows you to specify the width of a column with respect to the total width available.
For example, if you have a grid with three columns and set their StarWidth property to "4*", "*", and "*", the three columns will fill the entire width of the grid and the first one will be four times wider than the other two. If the user resizes the form and makes the grid wider, the columns will resize automatically to keep those proportions.
Star sizing makes the traditional ExtendLastCol property obsolete. If you set the StarWidth of the last column to "*", it will automatically fill the grid. But star sizing is a lot more powerful and flexible, because it allows you to extend any set of columns, not just the last one, and to specify how the space should be distributed among them.
For even more control, use the new MinWidth and MaxWidth properties to constrain the star sizing and prevent columns from getting too wide or too narrow.
You can set these properties in code, or you can use the design time editor to set their values. To use the designer, follow these steps:
- Select the grid on the form’s design surface,
- Set the grid’s DataSource property to create the columns automatically,
- Press F4 to see the grid’s property grid,
- Click the ellipsis button next to the Cols property to invoke the editor,
- Click each column in the designer and set its StartSize property to the desired value such as “4*”, “0.5”, or “*”.
Click the ellipsis button next to the Cols property to invoke the Column Designer:
Select the column and set its StarWidth property.
You can also set the MinWidth and MaxWidth properties in the editor.
Once you are done, run the project and resize the form to see the star sizing in action:
The top grid spreads the columns so they fit the grid width exactly. The bottom grid uses the MinWidth property to prevent the columns from getting too narrow, so the columns do not fit in the space available.
If you make the form wider, the columns automatically resize as shown below:
Happy development using ComponentOne!
If you have any questions about this tutorial, please leave us a comment. Additionally, if you have a request for a specific demo, be sure to leave a comment below!