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

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...