Skip to main content

Merging columns in GridView/DataGrid header



Background

As necessity to show header columns in a few rows occurs fairly often it would be good to have such functionality in the GridView/DataGrid control as an in-built feature. But meanwhile everyone solves this problem in his own way.
The described below variant of the merging implementation is based on irwansyah's idea to use the SetRenderMethodDelegate method for custom rendering of grid columns header. I guess this approach can be simplified in order to get more compact and handy code for reuse.

The code overview


As it may be required to merge a few groups of columns - for example, 1,2 and 4,5,6 - we need a class to store common information about all united columns.
  
[Serializable]
private class MergedColumnsInfo
{
    // indexes of merged columns
    public List<int> MergedColumns = new List<int>();
    // key-value pairs: key = the first column index, value = number of the merged columns
    public Hashtable StartColumns = new Hashtable();
    // key-value pairs: key = the first column index, value = common title of the merged columns 
    public Hashtable Titles = new Hashtable();
    
    //parameters: the merged columns indexes, common title of the merged columns 
    public void AddMergedColumns(int[] columnsIndexes, string title)
    {
        MergedColumns.AddRange(columnsIndexes);
        StartColumns.Add(columnsIndexes[0], columnsIndexes.Length);
        Titles.Add(columnsIndexes[0], title);
    }
}
Attribute Serializable is added in order to have a possibility to store information about merged columns in ViewState - it is required if paging or sorting is used.
That is the only additional action. Now the code usage.
.ascx file:
//for GridView
<asp:GridView ID="grid" runat=server OnRowCreated="GridView_RowCreated" ... ></asp:GridView>
//for DataGrid
<asp:DataGrid ID="grid" runat=server OnItemCreated="DataGrid_ItemCreated" ... ></asp:DataGrid>
Columns can be defined in design time or can be auto generated - it does not matter and doesn't influence the further code. Merging also does not harm sorting and paging if they are used in the GridView/DataGrid.
.cs file:
//property for storing of information about merged columns
private MergedColumnsInfo info
{
    get
    {
        if (ViewState["info"] == null)
            ViewState["info"] = new MergedColumnsInfo();
        return (MergedColumnsInfo)ViewState["info"];
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //merge the second, third and fourth columns with common title "Subjects"
        info.AddMergedColumns(new int[] { 1, 2, 3 }, "Subjects");
        grid.DataSource = ... //some data source
        grid.DataBind();
    }
}

Particular code for GridView:
protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
    //call the method for custom rendering the columns headers 
    if (e.Row.RowType == DataControlRowType.Header)
        e.Row.SetRenderMethodDelegate(RenderHeader);
}

and for DataGrid:
protected void DataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
    //call the method for custom rendering the columns headers 
    if (e.Item.ItemType == ListItemType.Header)
        e.Item.SetRenderMethodDelegate(RenderHeader);
}
Next code is common for both GridView and DataGrid:
//method for rendering the columns headers 

private void RenderHeader(HtmlTextWriter output, Control container)
{
    for (int i = 0; i < container.Controls.Count; i++)
    {
        TableCell cell = (TableCell)container.Controls[i];
 //stretch non merged columns for two rows
        if (!info.MergedColumns.Contains(i))
        {
            cell.Attributes["rowspan"] = "2";
            cell.RenderControl(output);
        }
        else //render merged columns common title
     if (info.StartColumns.Contains(i)) 
        {
            output.Write(string.Format("<th align='center' colspan='{0}'>{1}</th>", 
                     info.StartColumns[i], info.Titles[i]));
        }
    }
   
    //close the first row 
    output.RenderEndTag();
    //set attributes for the second row
    grid.HeaderStyle.AddAttributesToRender(output);
    //start the second row
    output.RenderBeginTag("tr");
    
    //render the second row (only the merged columns)
    for (int i = 0; i < info.MergedColumns.Count; i++)
    {
        TableCell cell = (TableCell)container.Controls[info.MergedColumns[i]];
        cell.RenderControl(output);
    }
}
That is all. The code can be used without any modification, the only part that has to be changed in a concrete case is:
info.AddMergedColumns(new int[] { 1, 2, 3 }, "Foo");
info.AddMergedColumns(new int[] { 6, 7 }, "Bar"); 
//and so forth ...
Download code - 2.6 Kb

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to solve this browser compatibility proble

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour