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.
Contributed by Wouter van Vugt Rating: / 24 January 14, 2004
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.
Trying to rebuild a control can not always be done as easily as we would sometimes like. There are several problems that need to be overcome when trying to implement the new features. For starters, the first uneditable column has width. This makes the calculation of the actual grid width a bit difficult. The picture above shows this area, the column before the ‘ID’ column.
Next, the DataGridColumnStyles that make up the DataGrid do not have a Visible property, thus making them hard to hide. And for the resizing of the rows, you really don’t want to know how that works. Although the final code is quite easy, there were some problems with re-sorting and filtering the DataGrid; however, those problems are solved now. Let’s handle each problem separately.
Calculating the Grid Width
While calculating the width of the grid can be easily achieved, there is only one setback: there must be rows present in the viewed DataSource. This is because the width of the first uneditable column is calculated by obtaining the X position of the first cell. No cell, no width. When there are no rows, a default value is used.
Hiding the Grid Columns
Each column in the DataGrid is represented by a DataGridColumnStyle object. This is the object that houses the width property which the columns adhere to. After working with the DataGrid I noticed that it’s impossible for the user to resize a column to a width of zero. So it’s possible for us to use that width to make the column invisible. We can also make use of this for checking whether a column is visible or not. This is necessary because we don’t want the auto sizing behavior to resize hidden columns, making them visible again. Setting the width to zero hides the column and will act like a switch when auto resizing the column widths.
Resizing the Row Heights
This was the hardest nut to crack. The first problem that I faced was finding out how the sizing of a single row works. Searching the documentation turned up a method in the DataGridColumnStyle called GetMinimumHeight; this, of course, peaked my interest.
I started playing around with the method, first making it return a higher value than normal. Wham! The rows resize. This really is the method that does the work! Now that the right method has been found, we need to find out for which cell GetMinimumHeight is called for; or maybe it’s called on a row-by-row basis?
Finding out was a bit harder than it would seem. The GetMinimumHeight does not supply any parameters that can be used, possibly leaving it next to impossible to guess which cell is queried for its height. The best way to solve this problem is adding debug statements and playing around with the code. We need to find the pattern of the GetMinimumHeight calling mechanism. When the pattern is known, it will be possible to link this pattern to specific rows or cells. The debug statements revealed the calling pattern quickly enough. It’s on a cell-by-cell basis, quite logical because we’re working with columns here.
The second problem was how to obtain the correct text to measure. Again the DataGridColumnStyle has a method available that might help. It’s called GetColumnValueAtRow, and it will need a CurrencyManager whatever that is) for obtaining the values. This now shifts our problem to obtaining a CurrencyManager. The documentation helps out again. In the documentation an example of how to obtain the CurrencyManager is shown. I tried it out, and did obtain correct string values.
Nice, second problem solved.
It is now possible to implement our own mechanism. It will need to count how many times the GetMinimumHeight method is called, and return a string height using the GetColumnValueAtRow method and a CurrencyManager obtained from the grid. When the count reaches the number of rows in the displayed source, the counter will need to be reset. This will allow for more dynamic behavior (not doing so will totally ruin the program when sorting, adding, or filtering, try it out). The resetting of the counter was the last problem with which I was faced. At times, the DataSource wouldn’t return the right number. After trying some other possibilities, the CurrencyManager turned out to be the correct source for the information required.
The code below is a cutout from the overridden GetMinimumHeight method, it shows the simplicity of the mechanism, and is all that is needed for row height sizing!
// Get CurrencyManager
CurrencyManager cur = (CurrencyManager)this.DataGridTableStyle.
As the introduction stated, the new DataGrid implements autosizing behavior. In this section I will explain the functions offered.
First let’s talk a bit about the auto width. The grid will attempt to resize the columns so they fit exactly in the ClientSize.Width. It will resize all columns equally, except those that have been resized by the user; those columns will stay their set size (read the acknowledgement section about this idea). The columns will never automatically resize smaller than the PreferredColumnWidth, which can be set in the DataGrid.
Hiding the columns is performed by setting their width to zero. A ContextMenu is provided for showing and hiding the columns. It can be brought up by right clicking anywhere in the grid. It also houses two resetting options, one for the width of the columns, the other for resetting the auto size behavior of columns that have been sized by the user.
The row heights are performed automatically. The only thing that has to be done is adding the right DataGridTableStyle (one with the supplied DataGridColumnStyle for each column) to the TableStyles collection of the grid. This can be done by calling the style creation method supplied with the grid.
There is a demo project supplied which shows a form, a grid and some buttons. It demonstrates that automatic resizing works while sorting, filtering or adding new rows. Play with it and be amazed! (I hope...)
Problems
As for problems, there is only one small one so far. Do not change the ReadOnly property of the grid to false. This will cause the row counter for the auto height to fail. You could do it, but expect to recalculate the currentIteration counter in the DataGridColumnStyle supplied in the source. You probably won’t want to make those changes; my User Interface Design teacher once told me “DataGrids are for viewing ONLY.”
Finally, a DataGrid with some proper sizing functions is implemented and now available. I found some resizing algorithms on the internet, but there was never one available that resized the row heights, which is my biggest annoyance. Now it’s available and ready for the next challenge: text wrapping. That’s just around the corner!
I tested the new control, but now it faces its biggest test, you. Please let me know of any problems that arise while using this control. Again, never, ever set the ReadOnly property to false unless you want trouble.