Monday, May 24, 2004

Inserting data via a DataGrid footer row

(a.k.a.: How to retrieve footer row contents on postback)
(a.k.a.: DataGrid's Nasty Underbelly)

Adding a footer row to a DataGrid is a cake-walk. Getting to the footer's contents on postback is a whole different ball of wax!

Why should you want to get the contents? Because it provides a very elegant mechanism for inserting a new row into the DataGrid (and the DataSet behind it, etc.) Ok, so how can we make this work?

When debugging, you will find that DataGrid.Controls[0] is a DataGridTable. So you attempt to cast this in your code, but then you find that DataGridTable is not instantiable. What to do, what to do? If you can just get to the DataGridItem for the footer, then you can use FindControl to get each control in your footer. To cut to the chase, here is what you need to do:

  • Get a WebControls.Table object from the DataGrid
  • Use the Table to determine the index position of the footer row
  • Acquire the footer row as a DataGridItem
  • Use DataGridItem.FindControl to locate each control on the row, casting each appropriately

By way of an example:
   Table tbl = dataGrid.Controls[0];
   int idxFooter = tbl.Rows.Count - 1;
   DataGridItem gridItem = tbl.Rows[idxFooter] as DataGridItem;
   //Assuming a TextBox named UserName was defined in the footer template...
   TextBox name = gridItem.FindControl("UserName") as TextBox;

Now you can use the TextBox as usual! To insert the data to the back-end datastore (XML, RDBMS, etc.), I like to create a new row in the DataSet table and use a DataAdapter to update (using the InsertCommand in this case).

No comments: