Displaying the Column Headers of a GridView

The GridView of ASP.NET 2.0 will not display column headers if there is no data. The following is a workaround, assuming that you have added two BoundField columns to your GridView:

[C#]
DataTable dt = new DataTable();
dt.Columns.Add(”Description”);
dt.Columns.Add(”Amount”);
dt.Rows.Add(dt.NewRow());
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan
  = GridView1.Columns.Count;

The last two lines are not strictly necessary; I have included them so that the resulting HTML output will have <td colspan="x"></td> between <tr> ... </tr>.

22 November 2006 | Software engineering, ASP.NET | Comments

Comments:

  1.  
  2.  
  3.