5,286,006 members and growing! (20,689 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate License: The Code Project Open License (CPOL)

Merge DataGrid Header

By irwansyah

Shows how to merge DataGrid header at run-time.
C#, Windows, .NET 1.0, .NET 1.1, .NET, ASP.NET, VS, VS.NET2003, Dev

Posted: 26 Oct 2004
Updated: 26 Oct 2004
Views: 152,739
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
40 votes for this Article.
Popularity: 6.72 Rating: 4.20 out of 5
3 votes, 7.5%
1
1 vote, 2.5%
2
1 vote, 2.5%
3
9 votes, 22.5%
4
26 votes, 65.0%
5

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


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.
Occupation: Web Developer
Location: Indonesia Indonesia

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralVB Versionmembermeme me6:00 20 May '08  
GeneralThis moves the grid below the page footer.membertech16:15 10 Mar '08  
Generalproblem when I am creating dynamic gridsmemberForwardmurali0:08 21 Sep '07  
GeneralSimplified and improved version the solution described above.memberMykola Tarasyuk4:33 13 Jun '07  
QuestionProblem with page [modified]membermaya_zakry20:59 30 May '07  
GeneralProblem with dynamic columnsmembersatejprabhu23:30 25 Feb '07  
QuestionWhat about Sorting and Paging ?membercodeprojectmitu0:51 10 Nov '06  
GeneralSorting Doesent work where RowSpan=2memberAnand Morbia5:49 14 Oct '06  
GeneralHelp to Merge it in VB.NET version...memberslee_g23:43 4 Sep '06  
QuestionSolution for Windows Form DataGridViewmemberC#newcomer18:04 18 Aug '06  
GeneralThanks (and some critics)membernsimeonov10:00 12 Jul '06  
GeneralRe: Thanks (and some critics)memberirwansyah16:25 12 Jul '06  
GeneralRe: Thanks (and some critics)membernsimeonov16:43 12 Jul '06  
GeneralProblem with ItemCommand eventmemberArturo Montoya Rivera13:50 23 Mar '06  
GeneralRe: Problem with ItemCommand eventmemberArturo Montoya Rivera6:08 24 Mar '06  
GeneralRe: Problem with ItemCommand eventmemberJakeanson0:51 28 Apr '06  
GeneralTHANK YOU!membersroh15:39 3 Mar '06  
GeneralProblem with Invisible Columnmembernavinkaus22:55 11 Jan '06  
GeneralDropdownList in Merged HeadermemberDick Clark1:39 9 Dec '05  
GeneralDropDownList in headermemberDick Clark1:38 9 Dec '05  
QuestionOverlapping titlesmemberrevie22:19 24 Nov '05  
GeneralGood ArticlememberFrancisFoo21:11 1 Sep '05  
GeneralExcellent detailsmembersambathraj.varadarajalu@csshome.net7:22 26 Jul '05  
Generalcan't sort on the added cell?membermargiex1:16 5 Jul '05  
GeneralVB.NETmembereirikr13:10 26 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Oct 2004
Editor: Smitha Vijayan
Copyright 2004 by irwansyah
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project