Click here for a larger image.
Environment: C#, Windows
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
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 comboboxes 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 at all.
Auto sizing row heights is the keyword. After using the
DataGrid, I found that the rows wouldn't resize automatically. A multiple line text shows as a single line row! Look at the picture below to see what the
DataGrid looks like in its normal state.
Forget about the ugly buttons on top (Filter & Add); this is the picture of the demo application without the autosizing enabled. The buttons are 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 texts 'long' and 'medium'? Yup, there's more data down there somewhere. The 'long' lines are actually three lines, the 'medium' ones are two. Also, notice the ugly piece of background shown beside the last column. This calls for some remodeling of the
In this article, building a customized
DataGrid that is able to automatically resize the column's width and the row's height will be achieved. And as a bonus, I will throw in hiding and showing columns on demand. We'll call the new control
AutoSizeDataGrid. The picture below shows how the grid will look; the picture is again taken from the test application included in the download, now enabled.
As you can see, the empty space behind the last column is now filled, and it will stay that way when resizing the grid. Also, the rows are drawn with their correct heights, greatly improving the readability of the data shown.
The Problems Faced
Trying to rebuild a control cannot always be done as easily as you would 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.
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. The final code is quite easy, however; there were some problems with re-sorting and filtering the
DataGrid, but those problems are solved now.
Let's handle each problem separately.
Calculating the grid width
This can be easily achieved; there is only one setback. There have to 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 that the columns adheres 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
GetMinimumHeight. This of course piqued 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 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. We need to find the pattern of the
GetMinimumHeight calling mechanism. When the pattern is known, it will be possible to link the pattern to specific rows or cells. The debug statements revealed the calling pattern quickly enough. It's on a 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 shifts the problem to obtaining a
CurrencyManager; the documentation helps out again. In the docs 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).
Resetting the counter was the last problem faced. The
DataSource wouldn't return the right number sometimes. 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's needed for row height sizing!
// Get CurrencyManager CurrencyManager cur = (CurrencyManager)this.DataGridTableStyle. DataGrid.BindingContext[this.DataGridTableStyle.DataGrid. DataSource, this.DataGridTableStyle.DataGrid.DataMember]; // Rows available? if(cur == null || cur.Count == 0) return base.GetMinimumHeight(); // Increment counter this.currentIteration++; // Initialize return value int retVal = base.GetMinimumHeight(); // Calculate height of row at currentIteration - 1 retVal = this.CalcStringHeight(GetColumnValueAtRow(cur, currentIteration - 1).ToString()); // Reset when last cell reached if(currentIteration == cur.Count) this.ResetIterations(); // sets currentIteration to 0 // Return return retVal;
The Solution Offered
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 the same amount, except those that have been resized by the user; those columns will stay their set size. Read the acknowledgement about this idea. The columns will never automatically resize smaller than the
PreferredColumnWidth, which can be set in the
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, and one for resetting the auto size behavior of columns that have been sized by the user.
The row heights are done 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 that shows a form, a grid, and some buttons. It demonstrates that automatic resizing works when sorting, filteringn or adding new rows. Play with it and be amazed (I hope).
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. But, you probably won't want to; my User Interface Design teacher once told me '
DataGrids are for viewing ONLY'.
The idea to resize all columns the same amount, and overriding the autosizing when the user has resized the column was borrowed from Mike Griffin. Read all about his DataGrid.
Thank you, Mike! Hope you like the row sizing.
DataGrid with some proper sizing functions is implemented and available. I found some resizing algorithms on the Internet, but there was never one available that resized the row heights, my biggest annoyance. Now, it's available and ready for the next challenge, text wrapping. It's around the corner now!
I tested the new control, but now it faces its biggest test, YOU. Please let me know of any problems that arise when using this control. But never, ever, ever set the
ReadOnly property to false unless you want trouble.
DownloadsDownload source code - 42 Kb
Download demo project - 27 Kb