Automatic Row Height in DataGrids
(Page 1 of 3 )
It looks like everyone is annoyed with the CSharp implementation of Windows controls. Textboxes, combos and DataGrids are popping up like mushrooms. After building a graphical debugging tool, I too became annoyed with one control in particular; the DataGrid. In this article, building a customized DataGrid that is capable of automatically resizing the column’s width and the row’s height will be achieved. As a bonus, I will throw in the capability of hiding and showing columns on demand.
There are loads of things that this control has built in: data binding, some events, and a professional view are available. Next to that, there are also a lot of customized implementations available for adding combo boxes to the grid, or making the columns automatically size their widths. But despite all of this, there is, at least, one thing that is still not found in the feature set.
Auto sizing row heights is the key phrase. After using the DataGrid I found that the rows do not resize automatically. A multiple line text entry shows as a single-lined row! Look at the picture below to see what the DataGrid looks like in its normal state.

Don’t worry about the ugly buttons on top (Filter & Add), as this is the picture of the demo application without the autosizing enabled. The buttons are simply for showing the height calculation still works while adding, or filtering, the rows in autosizing mode.
The grid is displaying a typed dataset I made for the debugging tool. Notice the words ‘long’ and ‘medium’? Yup, there’s more data down there somewhere. The ‘long’ lines are actually three lines in length; the ‘medium’ ones are two. Also, notice the unsightly background shown beside the last column. This calls for some remodeling of the DataGrid.
In this article, building a customized DataGrid that is capable of automatically resizing the column’s width and the row’s height will be achieved. As a bonus, I will throw in the capability of hiding and showing columns on demand. The picture below shows how the grid will look. The picture is again taken from the test application included in the download, which is now enabled.

As you can see the empty space behind the last column is now filled, and it will stay that way while resizing the grid. Also, the rows are drawn with their correct heights, greatly improving the readability of the data shown.
Next: The Problems Faced with the DataGrids >>
More C# Articles
More By Wouter Van Vugt