The DataGrid control is rendered as an HTML table, and its actual size can vary depending on several factors including the font, the length of the text, and the number of items displayed. When youre paging through a data source using a grid control, it becomes annoying when portions of the pages body move a few pixels up or down each time the height or the width of the grid changes.
Setting the Width property of each column to a specified maximum number of pixels allows you to maintain the width of the grid fixed. The same trick doesnt work for the heightfor a couple of reasons.
If you use a fixed width for each column and the actual text to be displayed exceeds the space, then the text may be wrapped, thus making the grid taller. You can work around this issue by setting the NoWrap attribute on the table cell.
If you give the grid a fixed height, another drawback may occur when the last page of the pageable grid is displayed. The last page of a grid normally contains a smaller number of items than other pages. As a result, all rows in the table are vertically stretched so that the grid occupies the fixed height entirely.
To guarantee that all rows are rendered with the natural height, and as many rows as other pages are displayed, you can only pad the bound data source with empty rows. Prior to binding to the grid, you preprocess the data source so that the total number of rows is a multiple of the page size. However, this approach is not free from problems either. Adding an empty row to a DataTable can be problematic if the DataTable object has constraints set or a primary key defined.
To ensure that the grid always displays in a fixed and closed area of the page, you must resort to the following trick, which also has the advantage of being totally declarative. The idea is that you wrap the DataGrid control in a fixed height HTML table. The wrapper table must have an empty row at the bottom, as shown below.
<table style="..." bgcolor="..."> <tr><td><asp:datagrid .../></td></tr> <tr><td height="100%"></td></tr> </table>
The unique cell of the bottom row must have a 100 percent height so that it will automatically occupy any space left by the topmost grid. Modifying two other visual settings can perfect the solution: First, use a borderless DataGrid and define border settings on the table; second, use the same background color for the table and the grid. The effect is guaranteed.
Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant based in Rome, Italy. Dino is a contributing editor to Windows Developer Magazine and MSDN Magazine, and the author of several books for Microsoft Press including Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET. Contact Dino at [email protected].