If you are wondering a way to change the column header appearing in the .Net GridView control in run time then this post will help you to get it done.
For example think that you need to change the normal grid headers shown in Screen A into something like shown in Screen B.
Screen A
Screen B
I have removed few columns from the grid header and then I did add few customized column headers. The added “Edit” column and “Id” column are spanning to 2 rows, the “Temp Columns” column is spanning to 2 columns.
I think the code is self explanatory. This way you will be able to create complex gridview headers.
- protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.Header)
- {
- // Remving the first two colummn headers.
- e.Row.Cells.RemoveAt(0);
- e.Row.Cells.RemoveAt(0);
- // Creating the gridview row object.
- GridViewRow headerGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Selected);
- headerGridRow.ID = "hdrGridRow";
- TableCell HeaderCell;
- // Creating and adding the first header cell.
- HeaderCell = new TableCell();
- HeaderCell.Text = "Edit";
- HeaderCell.ID = "cellEdit";
- HeaderCell.Font.Bold = false;
- HeaderCell.HorizontalAlign = HorizontalAlign.Center;
- HeaderCell.RowSpan = 2; // Spans across 2 rows.
- HeaderCell.ColumnSpan = 1;
- HeaderCell.BackColor = System.Drawing.Color.LightGray;
- HeaderCell.BorderColor = System.Drawing.Color.White;
- HeaderCell.ForeColor = System.Drawing.Color.Red;
- headerGridRow.Cells.Add(HeaderCell);
- // Creating and adding the second header cell.
- HeaderCell = new TableCell();
- HeaderCell.Text = "Id";
- HeaderCell.ID = "cellId";
- HeaderCell.Font.Bold = false;
- HeaderCell.HorizontalAlign = HorizontalAlign.Center;
- HeaderCell.RowSpan = 2;
- HeaderCell.ColumnSpan = 1;
- HeaderCell.BackColor = System.Drawing.Color.LightGray;
- HeaderCell.BorderColor = System.Drawing.Color.White;
- HeaderCell.ForeColor = System.Drawing.Color.Red;
- headerGridRow.Cells.Add(HeaderCell);
- // Creating and adding the third header cell.
- HeaderCell = new TableCell();
- HeaderCell.Text = "Temp Columns";
- HeaderCell.ID = "cellTempColumns";
- HeaderCell.Font.Bold = false;
- HeaderCell.HorizontalAlign = HorizontalAlign.Center;
- HeaderCell.RowSpan = 1;
- HeaderCell.ColumnSpan = 2; // Spans across 2 columns.
- HeaderCell.BackColor = System.Drawing.Color.LightGray;
- HeaderCell.BorderColor = System.Drawing.Color.White;
- HeaderCell.ForeColor = System.Drawing.Color.Red;
- headerGridRow.Cells.Add(HeaderCell);
- // Adding the header row to the gridview.
- GridView1.Controls[0].Controls.AddAt(0, headerGridRow);
- }
- }
-