views:

1118

answers:

2

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?

A: 

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:

private void InsertDataGridRow(DataGrid dataGrid, int index, TableCell tc)
{
 DataGridItem di = new DataGridItem(index, 0, ListItemType.Item);

 // Check which columns are visible
 bool foundFirstVisibleColumn = false;
 int numberOfVisibleColumns = 0;
 foreach (DataGridColumn column in dataGrid.Columns)
 {
  if (column.Visible == true)
  {
   numberOfVisibleColumns++;
   foundFirstVisibleColumn = true;
  }

  // Add dummy columns in the columns that are hidden
  if (!foundFirstVisibleColumn)
  {
   di.Cells.Add(new TableCell());
  }

 }

 tc.ColumnSpan = numberOfVisibleColumns;
 di.Cells.Add(tc);
 Table t = (Table)dataGrid.Controls[0];
 t.Rows.Add(di);
}

And the above can be called something like this:

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 tc = new TableCell();
  tc.Controls.Add(new LiteralControl("foo"));

  InsertDataGridRow(
            (DataGrid)sender,
            e.Item.ItemIndex + 1,
            tc);
 }      

}
tjrobinson
+1  A: 

I just tried an isolated example using the code you posted and it works just fine. It must be something to do with either the config of your DataGrid or something elsewhere in your code.

AdamRalph