Thursday, 25 November 2010

Vertical GridViews in ASP.net - Part 2b: Cell level rendering a GridViewRow

The key to the solution is the order in which the table cells are rendered out – in order to take over control of this we created a new class to wrap around the GridViewRow so that we could manually call the rendering on the actual cell we required. The structure of the class is quite simple:


  • A class variable to store the GridViewRow this is wrapping around
  • A constructor that takes in a GridViewRow and assigns it to the class variable
  • A render method that takes in a HTMLTextWriter, the index of the cell you want to render within the row, and a flag to indicate if this is to be rendered as a ‘header cell’ (more on the last in a post to follow)
All you need to do then is, within the render method get the correct  cell (of type DataControlFieldCell) within the Cells collection of the base GridViewRow, using the passed index.


If you’re not needing to output the cell as a header (i.e. render as a TH rather than a TD) all you need to do now is call the cell’s RenderControl method, passing in the HtmlTextWriter


If you do need to render as a header cell things aren’t quite as simple – header cells are actually set up during CreateChildControls as a different type -  DataControlFieldHeaderCell rather than DataControlFieldCell.
The simplest solution we found was creating a new DataControlFieldHeaderCell and manually copying the properties that we were interesting in preserving from the original cell (in our case CssClass, HorizontalAlign, and VerticalAlign), and then reassign the child controls from the original cell to the new cell:
 
while (OriginalCell.Controls.Count > 0)
{
  Control Child = OriginalCell.Controls[0];
  HeaderCell.Controls.Add(Child);
}


Once this is done call the header cell’s RenderControl as before.
 
I’ll leave it there for now, but will be post again soon with how to plumb this in to the standard control rendering

No comments:

Post a Comment