Thursday, April 30, 2009

Merge Header - Gridview/DataGrid


During development with GridView, we might come across many situations in which we need to extend GridView for our requirements. For example, we need to have a separate header other than the header provided by GridView. In that case we need to add new GridView item of header type. In this article we will see how merge two or more columns.


In this example we have simple GridView which is fetching data from xml file and displaying that in the table structure using GridView. In this GridView, we need to add two additional Header with text "Department" and "Employee". First department column should occupy first two columns and Employee column should occupy rest three columns.


I found in the internet that there are many ways to do this, but we might end up with column alignment problems.


Here we are going to see one of the best method to do that. To have additional header, we need to add one GridViewRow of header type to GridView inside OnRowCreated event method. The code snippet for doing this,

protected void GridView_Merge_Header_RowCreated(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.Header)
//Build custom header.
GridView oGridView = (GridView)sender;
GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell oTableCell = new TableCell();

//Add Department
oTableCell.Text = "Department";
oTableCell.ColumnSpan = 2;

//Add Employee
oTableCell = new TableCell();
oTableCell.Text = "Employee";
oTableCell.ColumnSpan = 3;
oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);

By Courtesy of Codeproject

No comments:

Post a Comment