Click here to Skip to main content
15,886,199 members
Articles / Web Development / ASP.NET

Merge Header - GridView/DataGrid

Rate me:
Please Sign up or sign in to vote.
4.39/5 (30 votes)
30 May 2008CPOL1 min read 231.2K   3.5K   69  
This article shows how we can merge multiple columns into a single column in a GridView using ASP.NET 2.0.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView_Merge_Header.DataSource = GenerateDataSet();
            GridView_Merge_Header.DataBind();
        }
    }

    private DataSet GenerateDataSet()
    {
        DataSet ds= new DataSet("test");
        ds.ReadXml(HttpRuntime.AppDomainAppPath + "/Employee.xml");
        return ds;
    }
    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;
            oGridViewRow.Cells.Add(oTableCell);

            //Add Employee
            oTableCell = new TableCell();
            oTableCell.Text = "Employee";
            oTableCell.ColumnSpan = 3;
            oGridViewRow.Cells.Add(oTableCell);

            oGridView.Controls[0].Controls.AddAt(0, oGridViewRow);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions