Click here to Skip to main content
11,436,179 members (66,457 online)
Click here to Skip to main content

Merge DataGrid Header

, 26 Oct 2004 CPOL
Rate this:
Please Sign up or sign in to vote.
Shows how to merge DataGrid header at run-time.

Sample Image

Sample Image

Introduction

This article describes the technique to merge the header of a DataGrid by redirecting the Render method of the DataGrid items.

Background

I found many times the need to merge the header of a DataGrid. So, when I was having spare time, I tried to find a way to do it, and here it is. I know that if you need to merge headers, you can use the Repeater control instead. But if you are fond of DataGrid (just like me), or may be you already used DataGrid, then this article is for you.

Using the code

When rendered, a DataGrid will be converted into a HTML Table element and the header will be the first HTML TR element. So, to have a merged header, we need to have control in the rendering of the header. This can be achieved by redirecting the Render method of the DataGrid header using the SetRenderMethodDelegate of the DataGrid header on ItemCreated event, like this:

private void Datagrid1_ItemCreated(object sender, 
          System.Web.UI.WebControls.DataGridItemEventArgs e) 
{ 
    //*** Examine if the item created is the header item 
    ListItemType lit = e.Item.ItemType; 
    if(ListItemType.Header == lit) 
    { 
        //*** Redirect the default header rendering method to our own method 
        e.Item.SetRenderMethodDelegate(new RenderMethod(NewRenderMethod)); 
    } 
}

And here is our own Render method:

/// <summary> 
/// This is our custom render method for the grid header item 
/// </summary> 
/// <param name="writer"></param> 
/// <param name="ctl"></param> 
private void NewRenderMethod(HtmlTextWriter writer, Control ctl) 
{ 
    //***  We don't need to write the <TR> tag
    //     because it's already written by the writer 
    //     so now we write the Name column 
    writer.Write("<TD colspan=\"3\" align=\"center\">Name</TD>\n"); 

    //***  The Age column must have the rowspan attribute
    //     and must be rendered inside the 
    //     first row so it will centered vertically 
    TableCell cell = (TableCell)ctl.Controls[ctl.Controls.Count-1]; 
    cell.Attributes.Add("rowspan","2"); 
    cell.RenderControl(writer); 

    //***     Now we close the first row, so we can insert the second one 
    writer.Write("</TR>\n"); 

    //***  Add the style attributes that was defined in design time 
    //     to our second row so they both will have the same appearance 
    DataGrid1.HeaderStyle.AddAttributesToRender(writer); 

    //***     Insert the second row 
    writer.RenderBeginTag("TR"); 

    //***  Render all the cells that was defined
    //     in design time, except the last one 
    //     because we already rendered it above 
    for(int i=0; i<= ctl.Controls.Count-2; i++) 
    { 
        ctl.Controls[i].RenderControl(writer); 
    } 

    //***  We don't need to write the </TR> close tag
    //     because the writer will do that for us 
    //     and so we're done :) 
}

I have created a decorator class to decorate a DataGrid (ASPNetDatagridDecorator class) to have a merge header, and all you need to do is define the header cell like this (you can use the auto format feature, but doesn't work for all):

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    if(!this.IsPostBack)
    {
        TableCell cell = null;
        DataGrid1.DataSource = GetData();
        DataGrid1.DataBind(); 

        m_add.DatagridToDecorate = Datagrid2;
        ArrayList header = new ArrayList();

        // cell = new TableCell();
        // cell.Text = "Code";
        // cell.RowSpan = 2;
        // cell.HorizontalAlign = HorizontalAlign.Center;
        // header.Add(cell);

        cell = new TableCell();
        cell.Text = "Name";
        cell.RowSpan = 2;
        cell.HorizontalAlign = HorizontalAlign.Center;
        header.Add(cell);

        cell = new TableCell();
        cell.Text = "Name";
        cell.ColumnSpan = 3;
        cell.HorizontalAlign = HorizontalAlign.Center;
        header.Add(cell);

        cell = new TableCell();
        cell.Text = "Age";
        cell.RowSpan = 2;
        cell.HorizontalAlign = HorizontalAlign.Center;
        header.Add(cell);

        cell = new TableCell();
        cell.Text = "School";
        cell.ColumnSpan = 3;
        cell.HorizontalAlign = HorizontalAlign.Center;
        header.Add(cell);

        cell = new TableCell();
        cell.Text = "Religion";
        cell.RowSpan = 2;
        cell.HorizontalAlign = HorizontalAlign.Center;
        header.Add(cell);

        m_add.AddMergeHeader(header);

        Datagrid2.DataSource = GetData();
        Datagrid2.DataBind();

    }

}

License

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

Share

About the Author

irwansyah
Web Developer
Indonesia Indonesia
Irwansyah is a web developer currently using ASP.Net. Irwansyah main interests lie in developing business application framework.

Irwansyah intends to work overseas one day and explore the world till the end of the world.

Comments and Discussions

 
GeneralMy vote of 1 Pin
shankar.koppella16-Aug-10 1:20
membershankar.koppella16-Aug-10 1:20 
QuestionProblem with row selecting Pin
Member 25375619-Jul-09 12:22
memberMember 25375619-Jul-09 12:22 
GeneralPage PostBack Pin
Goast25212-Mar-09 6:01
memberGoast25212-Mar-09 6:01 
GeneralPage PostBack Pin
MarichamyK9-Jul-09 19:57
memberMarichamyK9-Jul-09 19:57 
GeneralRe: Page PostBack Pin
isunshine4-Jan-10 12:17
memberisunshine4-Jan-10 12:17 
GeneralExcellent work...Keep it up Pin
Mohammed Hameed27-Jan-09 22:30
memberMohammed Hameed27-Jan-09 22:30 
QuestionAny solution for the sorting the dataGrid Pin
bpranathi14-Jul-08 11:03
memberbpranathi14-Jul-08 11:03 
GeneralVB Version Pin
meme me20-May-08 6:00
membermeme me20-May-08 6:00 
GeneralThis moves the grid below the page footer. Pin
tech110-Mar-08 6:15
membertech110-Mar-08 6:15 
Generalproblem when I am creating dynamic grids Pin
Forwardmurali21-Sep-07 0:08
memberForwardmurali21-Sep-07 0:08 
GeneralSimplified and improved version the solution described above. Pin
Mykola Tarasyuk13-Jun-07 4:33
memberMykola Tarasyuk13-Jun-07 4:33 
I try to simplify and improve the solution described above. Now it works with autogenerated columns, doesn't harm sorting and paging.
http://marss.co.ua/MergingGridViewHeaderColumns.aspx

QuestionProblem with page [modified] Pin
maya_zakry30-May-07 20:59
membermaya_zakry30-May-07 20:59 
GeneralProblem with dynamic columns Pin
satejprabhu25-Feb-07 23:30
membersatejprabhu25-Feb-07 23:30 
QuestionWhat about Sorting and Paging ? Pin
codeprojectmitu10-Nov-06 0:51
membercodeprojectmitu10-Nov-06 0:51 
GeneralSorting Doesent work where RowSpan=2 Pin
Anand Morbia14-Oct-06 5:49
memberAnand Morbia14-Oct-06 5:49 
GeneralHelp to Merge it in VB.NET version... Pin
slee_g4-Sep-06 23:43
memberslee_g4-Sep-06 23:43 
QuestionSolution for Windows Form DataGridView Pin
C#newcomer18-Aug-06 18:04
memberC#newcomer18-Aug-06 18:04 
GeneralThanks (and some critics) Pin
nsimeonov12-Jul-06 10:00
membernsimeonov12-Jul-06 10:00 
GeneralRe: Thanks (and some critics) Pin
irwansyah12-Jul-06 16:25
memberirwansyah12-Jul-06 16:25 
GeneralRe: Thanks (and some critics) Pin
nsimeonov12-Jul-06 16:43
membernsimeonov12-Jul-06 16:43 
GeneralProblem with ItemCommand event Pin
Arturo Montoya Rivera23-Mar-06 13:50
memberArturo Montoya Rivera23-Mar-06 13:50 
GeneralRe: Problem with ItemCommand event Pin
Arturo Montoya Rivera24-Mar-06 6:08
memberArturo Montoya Rivera24-Mar-06 6:08 
GeneralRe: Problem with ItemCommand event Pin
Jakeanson28-Apr-06 0:51
memberJakeanson28-Apr-06 0:51 
GeneralTHANK YOU! Pin
sroh3-Mar-06 15:39
membersroh3-Mar-06 15:39 
GeneralProblem with Invisible Column Pin
navinkaus11-Jan-06 22:55
membernavinkaus11-Jan-06 22:55 
GeneralDropdownList in Merged Header Pin
Dick Clark9-Dec-05 1:39
memberDick Clark9-Dec-05 1:39 
GeneralDropDownList in header Pin
Dick Clark9-Dec-05 1:38
memberDick Clark9-Dec-05 1:38 
QuestionOverlapping titles Pin
revie24-Nov-05 22:19
memberrevie24-Nov-05 22:19 
GeneralGood Article Pin
FrancisFoo1-Sep-05 21:11
memberFrancisFoo1-Sep-05 21:11 
GeneralExcellent details Pin
sambathraj.varadarajalu@csshome.net26-Jul-05 7:22
membersambathraj.varadarajalu@csshome.net26-Jul-05 7:22 
Questioncan't sort on the added cell? Pin
margiex5-Jul-05 1:16
membermargiex5-Jul-05 1:16 
GeneralVB.NET Pin
eirikr26-May-05 13:10
membereirikr26-May-05 13:10 
GeneralRe: VB.NET Pin
Christian Graus26-May-05 13:40
memberChristian Graus26-May-05 13:40 
GeneralRe: VB.NET Pin
Cliff_k1017-Apr-06 14:29
memberCliff_k1017-Apr-06 14:29 
GeneralRe: VB.NET Pin
Christian Graus9-Apr-06 12:50
memberChristian Graus9-Apr-06 12:50 
GeneralRe: VB.NET Pin
Lee hopkins30-Oct-07 11:44
memberLee hopkins30-Oct-07 11:44 
QuestionHow about Rowspan &gt; 2 ? Pin
CHAKCHAK17-May-05 22:24
sussCHAKCHAK17-May-05 22:24 
AnswerRe: How about Rowspan &gt; 2 ? Pin
mike_0123-May-05 0:07
membermike_0123-May-05 0:07 
GeneralRe: How about Rowspan &gt; 2 ? Pin
gdfgdfg25-Jul-05 19:00
membergdfgdfg25-Jul-05 19:00 
GeneralSimplification Pin
hastlaug21-Apr-05 14:36
memberhastlaug21-Apr-05 14:36 
GeneralThere is a bug when grid has invisible columns Pin
dududu3-Apr-05 22:02
memberdududu3-Apr-05 22:02 
GeneralRe: There is a bug when grid has invisible columns Pin
navinkaus11-Jan-06 22:56
membernavinkaus11-Jan-06 22:56 
GeneralItemDataBound is giving casting exception Pin
Anonymous17-Mar-05 18:02
sussAnonymous17-Mar-05 18:02 
GeneralWhere Can I Find this code in VB.net Pin
Ricardo Martinez22-Jan-05 20:45
sussRicardo Martinez22-Jan-05 20:45 
GeneralRe: Where Can I Find this code in VB.net Pin
Rodrigo Pires1-Feb-05 7:31
sussRodrigo Pires1-Feb-05 7:31 
GeneralRe: Where Can I Find this code in VB.net Pin
Ghalib Hamidi1-Oct-06 18:40
memberGhalib Hamidi1-Oct-06 18:40 
GeneralBig problem Pin
ddtudor2613-Jan-05 3:52
memberddtudor2613-Jan-05 3:52 
GeneralRe: Big problem (Solution) Pin
Tumurbaatar28-Nov-05 18:55
memberTumurbaatar28-Nov-05 18:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 27 Oct 2004
Article Copyright 2004 by irwansyah
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid