Merge merging or Split spliting GridView Header Row or columns in Asp.Net C# VB.Net

In most of the times for reporting purpose we need to merge or merging GridView header columns or rows or to use multiple headers in Asp.Net C# Vb.Net code. In this article or Asp.Net C# tutorial I will explain how one can merge or split GridView Header rows or columns. For this example here I took a sample easy Stock table with no ER. Where In first two columns I will show Brand Name & Category Name, after that splitting & will give a name hierarchy. Then I will display product name & after that I will show quantities & split & merge into three columns.

Objective/Outcome:
Merge merging or Split spliting GridView Header Row or columns in Asp.Net CSharp VB.Net

To do the Example First Create a Database Table:

CREATE TABLE [dbo].[tblStock](
	[BrandName] [varchar](max) NULL,
	[CategoryName] [varchar](max) NULL,
	[ProductName] [varchar](max) NULL,
	[LogicalQuantity] [bigint] NULL,
	[PhysicalQuantity] [bigint] NULL,
	[QuarentineQuantity] [bigint] NULL
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO tblStock VALUES('Kohinoor','Soap','Tibbet Handwash',55781,55780,1)
INSERT INTO tblStock VALUES('Kohinoor','Soap','Tibbet Soap',38786,38780,6)
INSERT INTO tblStock VALUES('Kohinoor','ToothPaste','Tibbet Clear',34503,34500,3)
INSERT INTO tblStock VALUES('Proctor & Gamble','Bubble','',43809,43800,9)
INSERT INTO tblStock VALUES('Telenor','Mobile','Data SIM',43876,43870,6)
INSERT INTO tblStock VALUES('Telenor','Mobile','GP Modem',23907,23900,7)
INSERT INTO tblStock VALUES('Uniliver','Soap','Lux',19806,19800,6)
INSERT INTO tblStock VALUES('Uniliver','TeleProducts','Brittle',20703,20700,3)
INSERT INTO tblStock VALUES('Uniliver','ToothPaste','Close Up',16755,16750,5)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now Add the GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
            <asp:BoundField DataField="BrandName" HeaderText="Brand Name" />
            <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
            <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
            <asp:BoundField DataField="LogicalQuantity" HeaderText="Logical" />
            <asp:BoundField DataField="PhysicalQuantity" HeaderText="Physical" />
            <asp:BoundField DataField="QuarentineQuantity" HeaderText="Quarentine" />
        </Columns>
        </asp:GridView>

Now Bind GridView:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM [tblStock]", conn);
                cmd.CommandType = CommandType.Text;
                conn.Open();
                SqlDataReader drStock = cmd.ExecuteReader();
                GridView1.DataSource = drStock;
                GridView1.DataBind();
            }
        }
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
                Dim cmd As New SqlCommand("SELECT * FROM [tblStock]", conn)
                cmd.CommandType = CommandType.Text
                conn.Open()
                Dim drStock As SqlDataReader = cmd.ExecuteReader()
                GridView1.DataSource = drStock
                GridView1.DataBind()
            End Using
        End If
    End Sub

Now need to mastering GridView RowCreated event like below:
C# Code:

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell Cell_Header = new TableCell();
            Cell_Header.Text = "Hierarchy";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Product Name";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 1;
            Cell_Header.RowSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Quantity";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 3;
            HeaderRow.Cells.Add(Cell_Header);

            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

        }
    }

VB.Net Code:

    Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.Header Then
            Dim HeaderGrid As GridView = DirectCast(sender, GridView)
            Dim HeaderRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
            Dim Cell_Header As New TableCell()
            Cell_Header.Text = "Hierarchy"
            Cell_Header.HorizontalAlign = HorizontalAlign.Center
            Cell_Header.ColumnSpan = 2
            HeaderRow.Cells.Add(Cell_Header)

            Cell_Header = New TableCell()
            Cell_Header.Text = "Product Name"
            Cell_Header.HorizontalAlign = HorizontalAlign.Center
            Cell_Header.ColumnSpan = 1
            Cell_Header.RowSpan = 2
            HeaderRow.Cells.Add(Cell_Header)

            Cell_Header = New TableCell()
            Cell_Header.Text = "Quantity"
            Cell_Header.HorizontalAlign = HorizontalAlign.Center
            Cell_Header.ColumnSpan = 3
            HeaderRow.Cells.Add(Cell_Header)


            GridView1.Controls(0).Controls.AddAt(0, HeaderRow)
        End If
    End Sub

One another tricks is to merge middle row for product name. Here i have merged the row cells within RowCreated event. The problem is we need to set visible false for bind column ‘product name’ in GridView HTML. To do that here i choose the GridView RowDataBound event. So that you can do what you require in runtime. Look how we can control to merging row cells:

C# Code:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.Cells[2].Visible = false;
    }

VB.Net Code:

    Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.Header Then
            e.Row.Cells(2).Visible = False
        End If
    End Sub

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Gridview, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*