I would like to programmatically insert additional rows into a DataGrid (to act as subheadings). I have followed a number of articles online (namely option 3 from http://aspalliance.com/723) but they all result in the row being displayed correctly, but with no contents.
Here is the important part of the code I’m using:
private void MyDataGrid_ItemCreated(object sender, DataGridItemEventArgs e) { // This method will create a subheading row if needed if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // TableCell TableCell tc = new TableCell(); tc.Controls.Add(new LiteralControl('foo')); tc.ColumnSpan = e.Item.Cells.Count; // DataGridItem DataGridItem di = new DataGridItem(e.Item.ItemIndex + 1, 0, ListItemType.Item); di.Height = new Unit(100, UnitType.Pixel); di.CssClass = 'testClass'; di.Controls.Add(tc); // DataGrid Table DataGrid dg = (DataGrid)sender; Table childTable = (Table)dg.Controls[0]; childTable.Rows.Add(di); } }
This results in the following markup being generated in the correct place, but without the LiteralControl(‘foo’)
<tr class='testClass' style='height:100px;'> </tr>
I would like to use this approach rather than manipulating the datasource itself. What could be going wrong?
Problem solved – somewhere in the 2500 lines of existing code-behind, something was hiding the first column, effectively removing my addition. Something to watch out for if anyone else has similar problems.
Edit – Here’s the code I’ve written to get round the problem in a reasonably generic way:
And the above can be called something like this: