Insert a Dynamic Row into a DataGrid August 1, 2007Posted by codinglifestyle in ASP.NET, C#.
Tags: datagrid, DataGridItem, gridview, ItemDataBound
DataGrids (v1.1) and GridViews (v2.0) are extremely powerful controls for displaying databound data such as a table from a DB. They also offer pagination and sorting for free. However, for all that power at the end of the day they merely render a standard HTML table. If you’re used to programmatically building your own tables and having special headers/footers or certain rows which behave differently the DataGrid can suddenly feel quite restricting.
Usually the place to start when cusomtizing the grid on the fly is the ItemDataBound event. Here we have access to the DataGridItem and DataRowView representing the specific row being bound. This allows us to easily test for certain conditions and modify the row. But this event really limits you to affecting just the row being bound.
Last week we needed to insert a new row under certain conditions. Again, the best place to test if a specific row met these conditions was the ItemDataBound event. If the condition was met, we wanted to add a row below the current row being bound. How do we do this?
While you have access to the current row’s cells and to the grid itself, there is no obvious way of adding a new row. The grid’s Items are available but these are bound to our datasource and looks like a dead end. But they aren’t. There is a way of adding in a new DataGridItem which translates to adding a new row. Here’s how you do it:
//Create an empty DataGridItem
DataGridItem itemDesc = new DataGridItem(0, 0, ListItemType.Item);
//This row will show the description of the item being bound
TableCell cellDesc = new TableCell();
cellDesc.Text = sDescription;
cellDesc.ColumnSpan = e.Item.Cells.Count;
//Add the new row to the table
Here we create a new DataGridItem and add cells which can contain text and/or their own controls. To insert the DataGridItem into the grid is the tricky part. We grab the first control in the DataGrid which is actually the DataGridTable. As we are binding row by row the DataGridTable.Controls are filling with DataGridItems. So, the DataGridTable.Controls only contains the DataGridItems bound thus far. Hence, when we add our new DataGridItem it is the next row.