How to Merge Wrap GridView Cells Or Columns in Row ASP.NET C# VB.Net

In most of the cases specially for reporting purpose we need to merge GridView cells or columns for client preferred output. In this example i will show you how one can merge GridView cells or columns in C# & VB.Net. My special focus is on to merge cells when both contains same or equal data. So that the GridView looks like a traditional report. For merging GridView cells here i am using a generic method so that you can isolate it into business layer.

How to Merge Wrap GridView Cells Or Columns in Row 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

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:

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

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.

Design the GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White">
         <asp:BoundField DataField="BrandName" HeaderText="Brand Name" ItemStyle-BorderStyle="Solid"/>
         <asp:BoundField DataField="CategoryName" HeaderText="Category Name" ItemStyle-BorderStyle="Solid"/>
         <asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-BorderStyle="Solid"/>

Now Bind GridView with Database:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DataTable dt;
            String SQL = "SELECT * FROM tblStock";

            string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                        dt = new DataTable("tbl");

            GridView1.DataSource = dt;

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable
            Dim SQL As [String] = "SELECT * FROM tblStock"

            Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Using conn As New SqlConnection(sConstr)
                Using comm As New SqlCommand(SQL, conn)
                    Using da As New SqlDataAdapter(comm)
                        dt = New DataTable("tbl")
                    End Using
                End Using
            End Using

            GridView1.DataSource = dt
        End If
    End Sub

Now implement GridView Cell Marging Function:
C# Code:

    public void GridView_Row_Merger(GridView gridView)
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            GridViewRow currentRow = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 0; i < currentRow.Cells.Count; i++)
                if (currentRow.Cells[i].Text == previousRow.Cells[i].Text)
                    if (previousRow.Cells[i].RowSpan < 2)
                        currentRow.Cells[i].RowSpan = 2;
                        currentRow.Cells[i].RowSpan = previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;

VB.Net Code:

    Public Sub GridView_Row_Merger(gridView As GridView)
        For rowIndex As Integer = gridView.Rows.Count - 2 To 0 Step -1
            Dim currentRow As GridViewRow = gridView.Rows(rowIndex)
            Dim previousRow As GridViewRow = gridView.Rows(rowIndex + 1)

            For i As Integer = 0 To currentRow.Cells.Count - 1
                If currentRow.Cells(i).Text = previousRow.Cells(i).Text Then
                    If previousRow.Cells(i).RowSpan < 2 Then
                        currentRow.Cells(i).RowSpan = 2
                        currentRow.Cells(i).RowSpan = previousRow.Cells(i).RowSpan + 1
                    End If
                    previousRow.Cells(i).Visible = False
                End If
    End Sub

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” Namespaces.

Download Code Example C#        Download Code Example VB.Net

6 thoughts on “How to Merge Wrap GridView Cells Or Columns in Row ASP.NET C# VB.Net

  • June 2, 2015 at 8:10 am

    Can you please assist me I am struggling with something on the gridview

    • June 2, 2015 at 9:43 am

      If any specific issue please share.

  • June 2, 2015 at 10:04 am

    Thanks Oky so the above sample works perfectly if I use.. BoundField but if I use TemplateField My grid-view only display the first entry. Ok so it is fine I will use the below value .. BoundField but I want to put in a button at the end so that I can run a command on each line, but if I put in a button using the TemplateField The button merge over all of the lines so I can\\\’t do a command per line. I hope you understand.

  • June 2, 2015 at 5:26 pm

    Please mail me your code & a visual diagram of your desired output. Please be specific on a single issue.

  • June 21, 2016 at 11:07 am

    i am using template field instead of bound field but i am able to see only first row. could you please help me ?


Leave a Reply

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

AlphaOmega Captcha Classica  –  Enter Security Code