navigation
 Friday, January 27, 2006

The MSDN Library says this about the DataGrid.Items property:

"Only items bound to the data source are contained in the Items collection. The header, footer, and separator are not included in the collection."

So how do we get to these other items? Most people handle the ItemCommandEvent for the grid, but there is a way to access them directly.

If these items are not in the DataGrid.Items collection, then where are they? To find out, turn on tracing for your ASP.NET webpage. You will see that the grid is rendered something like this:

DataGrid
   DataGridTable
      DataGridItem
         TableCell
         TableCell
      DataGridItem
         TableCell
         LiteralControl
         Label
      DataGridItem
      ...

What we are seeing is that the first object in the DataGrid's Control hierarchy is a DataGridTable. That DataGridTable contains ALL of the DataGridItems, including the header and footer. To get these DataGridItems we just need to grab the first or last control out of the DataGridTable's control collection.

So to get a DataGrid's footer, this code will do this trick:

//First get the DataGridTable (the first control in DataGrid's control collection.)
//Then grab the last control in the DataTable's Collection
DataGridItem footer = 
    DataGrid1.Controls[0].Controls[DataGrid1.Controls[0].Controls.Count -1] as DataGridItem;