Thursday, November 29, 2007

Merge Grid View Header in Asp.Net 2.0 (C#)

To merge headers of a grid view in .NET 2.0
let take a grid view and bound it's column to some data fields on .aspx page
and add event OnRowDataBound="gvEmployee_RowDataBound" to your grid view.
Now in code behind page
just make the method for "RowDataBound" ie
protected void
gvEmployee_RowDataBound(Object sender,GridViewRowEventArgs e) this method always get executed when a grid.bind() method called any where in your code.
So here it is

protected void gvEmployee_RowDataBound(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 = "Header Column1 name what ever you want";
oTableCell.ColumnSpan = 2;
oGridViewRow.Cells.Add(oTableCell);

//Add Employee
oTableCell = new TableCell();
oTableCell.Text = "
Header Column2 name what ever you want";
oTableCell.ColumnSpan = 3;
oGridViewRow.Cells.Add(oTableCell);
oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
}

}
Hence in the code as you can see that there are two column is being created as per your intrest
you can add your header .
I hope you will enjoy this code