Skip to main content

C#.Net - Programmatically Group Gridview Column Headers in ASP.Net,VB.Net

In this tutorial i am going to explain about how to programmatically group gridview column headers to give specific titles to the columns.

In my previous article i have explained about How To Convert JSON Data Into Html Table Using Javascript jQuery, Upload multiple files in asp.net C#.Net VB.Net / Maximum Request Length Exceeded, Change Row Color of a Grid view Based on Particular Condition C#.Net ASP.Net VB.Net, Fill Datatable and Bind GridView Using Data Reader in ASP.Net C#.Net VB.Net, how to get the selected values from checkboxlist in C#.Net and VB.Net, how to implement option group in asp.net drop down list, ASP.Net - Bind Array To DropDownList in C#.Net,VB.Net.


Grouping grid view column headers is achieved using on OnRowCreated even of the grid view.

For explanation purpose i have created a new empty asp.net website and added default.aspx file into the website. Inside the webform i have dragged grid view control from the toolbox and added to the web form and added the columns that i would like to display as the bound field with the headertext. I have mentioned some styles that can be used to render the grid view.

HTML Markup:

Grouping Grid View Column Header By .Net Pickles


I code behind file i have created a datatable and created some columns in that datatable to insert employee records. Once the table is created i have inserted the sample records and then binded that datatable to gridview. On OnRowCreated event of the grid view the master header that is the columns are grouped and master header is added. Below is the code.

C#.Net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    // Columns to store personal details
    dt.Columns.Add("EmpId", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Qualification", typeof(string));

    // Columns to store location details
    dt.Columns.Add("Location", typeof(string));
    dt.Columns.Add("Branch", typeof(string));

    // Columns to store salary details
    dt.Columns.Add("Designation", typeof(string));
    dt.Columns.Add("Department", typeof(string));
    dt.Columns.Add("Salary", typeof(string));

    // Adding sample rows
    DataRow drow;
    dt.Rows.Add(1, "Arun", "BTech", "Bangalore", "Branch1", "Developer", "Development Team", "$1000/Month");
    dt.Rows.Add(1, "Raghav", "BE", "Chennai", "Branch2", "Designer", "Design Team", "$1500/Month");
    dt.Rows.Add(1, "Anthony", "BCA", "Bangalore", "Branch1", "Tester", "Testing Team", "$2000/Month");
    dt.Rows.Add(1, "Saxena", "MTech", "Mumbai", "Branch2", "Project Manager", "Development Team", "$2500/Month");
    dt.Rows.Add(1, "Xavier", "MBA", "Chennai", "Branch1", "Product Manager", "Product Team", "$3000/Month");
    dt.Rows.Add(1, "Mustaffa", "MBA", "Mumbai", "Branch2", "Product Manager", "Product Team", "$3500/Month");

    //Binding datatable to grid view
    GridEmployeeDetails.DataSource = dt;
    GridEmployeeDetails.DataBind();

}

protected void GridEmployeeDetails_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

        TableCell MasterHeader = new TableCell();
            
        // First Three Coluns come under Personal Details
        // So ColumnSpan set to 3
        MasterHeader.Text = "Personal Details";
        MasterHeader.ColumnSpan = 3;
        HeaderRow.Cells.Add(MasterHeader);

        // 3rd & 4th Coluns come under Office Details
        // So ColumnSpan set to 2
        MasterHeader = new TableCell();
        MasterHeader.Text = "Office Details";
        MasterHeader.ColumnSpan = 2;
        HeaderRow.Cells.Add(MasterHeader);

        // 5th,6th & 7th Coluns come under Salary Details
        // So ColumnSpan set to 3
        MasterHeader = new TableCell();
        MasterHeader.Text = "Salary details";
        MasterHeader.ColumnSpan = 3;
        HeaderRow.Cells.Add(MasterHeader);

        GridEmployeeDetails.Controls[0].Controls.AddAt(0, HeaderRow);
    }
}
}

VB.Net:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data

Public Partial Class _Default
 Inherits System.Web.UI.Page
 Protected Sub Page_Load(sender As Object, e As EventArgs)
  Dim dt As New DataTable()
  ' Columns to store personal details
  dt.Columns.Add("EmpId", GetType(Integer))
  dt.Columns.Add("Name", GetType(String))
  dt.Columns.Add("Qualification", GetType(String))

  ' Columns to store location details
  dt.Columns.Add("Location", GetType(String))
  dt.Columns.Add("Branch", GetType(String))

  ' Columns to store salary details
  dt.Columns.Add("Designation", GetType(String))
  dt.Columns.Add("Department", GetType(String))
  dt.Columns.Add("Salary", GetType(String))

  ' Adding sample rows
  Dim drow As DataRow
  dt.Rows.Add(1, "Arun", "BTech", "Bangalore", "Branch1", "Developer", _
   "Development Team", "$1000/Month")
  dt.Rows.Add(1, "Raghav", "BE", "Chennai", "Branch2", "Designer", _
   "Design Team", "$1500/Month")
  dt.Rows.Add(1, "Anthony", "BCA", "Bangalore", "Branch1", "Tester", _
   "Testing Team", "$2000/Month")
  dt.Rows.Add(1, "Saxena", "MTech", "Mumbai", "Branch2", "Project Manager", _
   "Development Team", "$2500/Month")
  dt.Rows.Add(1, "Xavier", "MBA", "Chennai", "Branch1", "Product Manager", _
   "Product Team", "$3000/Month")
  dt.Rows.Add(1, "Mustaffa", "MBA", "Mumbai", "Branch2", "Product Manager", _
   "Product Team", "$3500/Month")

  'Binding datatable to grid view
  GridEmployeeDetails.DataSource = dt
  GridEmployeeDetails.DataBind()

 End Sub

 Protected Sub GridEmployeeDetails_RowCreated(sender As Object, e As GridViewRowEventArgs)
  If e.Row.RowType = DataControlRowType.Header Then
   Dim HeaderRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)

   Dim MasterHeader As New TableCell()

   ' First Three Coluns come under Personal Details
   ' So ColumnSpan set to 3
   MasterHeader.Text = "Personal Details"
   MasterHeader.ColumnSpan = 3
   HeaderRow.Cells.Add(MasterHeader)

   ' 3rd & 4th Coluns come under Office Details
   ' So ColumnSpan set to 2
   MasterHeader = New TableCell()
   MasterHeader.Text = "Office Details"
   MasterHeader.ColumnSpan = 2
   HeaderRow.Cells.Add(MasterHeader)

   ' 5th,6th & 7th Coluns come under Salary Details
   ' So ColumnSpan set to 3
   MasterHeader = New TableCell()
   MasterHeader.Text = "Salary details"
   MasterHeader.ColumnSpan = 3
   HeaderRow.Cells.Add(MasterHeader)

   GridEmployeeDetails.Controls(0).Controls.AddAt(0, HeaderRow)
  End If
 End Sub
End Class

The output will look like below
Output of C#.Net - Programmatically Group Gridview Column Headers in ASP.Net,VB.Net
You may also like:
  1. ASP.Net - Validate form using css in C#.Net
  2. How to change Placeholder text color on focus using css
  3. How to change placeholder text color
  4. ASP.Net - Bind Array To DropDownList in C#.Net,VB.Net
  5. Code to encrypt and decrypt files using C#.Net, ASP.Net
  6. Binding Gridview in Asp.net
  7. C# code to bind XML data to Grid view
  8. Change Row Color of a Grid view Based on Particular Condition C#.Net ASP.Net VB.Net 
  9. How to show confirm message while deleting grid view row.
  10. Select deselect all checkboxes in grid view using javascript
Sourcecode of programmatically grouping gridview column header in C#.Net VB.Net


Download sourcecode of Programmatically Group Gridview Column Headers in ASP.Net,VB.Net


Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...