Click here to Skip to main content
Click here to Skip to main content

Merge DataGrid Header

By , 26 Oct 2004
 

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)

About the Author

irwansyah
Web Developer
Indonesia Indonesia
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralSimplified and improved version the solution described above. PinmemberMykola Tarasyuk13 Jun '07 - 3:33 
QuestionProblem with page [modified] Pinmembermaya_zakry30 May '07 - 19:59 
GeneralProblem with dynamic columns Pinmembersatejprabhu25 Feb '07 - 22:30 
QuestionWhat about Sorting and Paging ? Pinmembercodeprojectmitu9 Nov '06 - 23:51 
GeneralSorting Doesent work where RowSpan=2 PinmemberAnand Morbia14 Oct '06 - 4:49 
GeneralHelp to Merge it in VB.NET version... Pinmemberslee_g4 Sep '06 - 22:43 
QuestionSolution for Windows Form DataGridView PinmemberC#newcomer18 Aug '06 - 17:04 
GeneralThanks (and some critics) Pinmembernsimeonov12 Jul '06 - 9:00 
GeneralRe: Thanks (and some critics) Pinmemberirwansyah12 Jul '06 - 15:25 
GeneralRe: Thanks (and some critics) Pinmembernsimeonov12 Jul '06 - 15:43 
GeneralProblem with ItemCommand event PinmemberArturo Montoya Rivera23 Mar '06 - 12:50 
GeneralRe: Problem with ItemCommand event PinmemberArturo Montoya Rivera24 Mar '06 - 5:08 
GeneralRe: Problem with ItemCommand event PinmemberJakeanson27 Apr '06 - 23:51 
GeneralTHANK YOU! Pinmembersroh3 Mar '06 - 14:39 
GeneralProblem with Invisible Column Pinmembernavinkaus11 Jan '06 - 21:55 
GeneralDropdownList in Merged Header PinmemberDick Clark9 Dec '05 - 0:39 
GeneralDropDownList in header PinmemberDick Clark9 Dec '05 - 0:38 
QuestionOverlapping titles Pinmemberrevie24 Nov '05 - 21:19 
GeneralGood Article PinmemberFrancisFoo1 Sep '05 - 20:11 
GeneralExcellent details Pinmembersambathraj.varadarajalu@csshome.net26 Jul '05 - 6:22 
Questioncan't sort on the added cell? Pinmembermargiex5 Jul '05 - 0:16 
GeneralVB.NET Pinmembereirikr26 May '05 - 12:10 
GeneralRe: VB.NET PinmemberChristian Graus26 May '05 - 12:40 
GeneralRe: VB.NET PinmemberCliff_k1017 Apr '06 - 13:29 
GeneralRe: VB.NET PinmemberChristian Graus9 Apr '06 - 11:50 
GeneralRe: VB.NET PinmemberLee hopkins30 Oct '07 - 10:44 
QuestionHow about Rowspan &gt; 2 ? PinsussCHAKCHAK17 May '05 - 21:24 
AnswerRe: How about Rowspan &gt; 2 ? Pinmembermike_0122 May '05 - 23:07 
GeneralRe: How about Rowspan &gt; 2 ? Pinmembergdfgdfg25 Jul '05 - 18:00 
GeneralSimplification Pinmemberhastlaug21 Apr '05 - 13:36 
GeneralThere is a bug when grid has invisible columns Pinmemberdududu3 Apr '05 - 21:02 
GeneralRe: There is a bug when grid has invisible columns Pinmembernavinkaus11 Jan '06 - 21:56 
GeneralItemDataBound is giving casting exception PinsussAnonymous17 Mar '05 - 17:02 
GeneralWhere Can I Find this code in VB.net PinsussRicardo Martinez22 Jan '05 - 19:45 
GeneralRe: Where Can I Find this code in VB.net PinsussRodrigo Pires1 Feb '05 - 6:31 
GeneralRe: Where Can I Find this code in VB.net PinmemberGhalib Hamidi1 Oct '06 - 17:40 
GeneralBig problem Pinmemberddtudor2613 Jan '05 - 2:52 
GeneralRe: Big problem (Solution) PinmemberTumurbaatar28 Nov '05 - 17:55 
GeneralRe: Big problem (Solution) PinmemberXiaoZhouShen12 Dec '05 - 22:22 
GeneralRe: Big problem (Solution) PinmemberuXses13 Aug '07 - 4:59 
GeneralRe: Big problem Pinmembergrayghot699 May '06 - 6:29 
GeneralDosen't Maintain View state. Pinmemberrohangandhi8 Jan '05 - 3:46 
GeneralRe: Dosen't Maintain View state. Pinmembermike_0122 May '05 - 23:00 
GeneralRe: Dosen't Maintain View state. (Solution) PinmemberTee+13 Jul '05 - 21:42 
GeneralRe: Dosen't Maintain View state. (Solution) PinmemberChristophe Liacopoulos13 Sep '05 - 20:16 
GeneralRe: Dosen't Maintain View state. (Solution) Pinmembergursoy9 Jun '06 - 8:45 
GeneralDisktop application PinmemberHossam Abbas4 Jan '05 - 14:26 
GeneralGreat Article PinmemberSanpra2614 Dec '04 - 11:16 

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 27 Oct 2004
Article Copyright 2004 by irwansyah
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid