Skip to main content

Merging Gridview Rows with same Column values in and C#

Here I am merging the Column of same value by comparing the next row. Merging is done by Rowspan Property and Executed in OnRowDataBound Event. To execute this the First column values should be repeated more than once to find the result. Find the code below.

Output preview :
Merging same value Cells in Gridview
 Database structure :
 your data Should Contain multiple values  of the same value to be Executed and should use order by to the row you are going to merge. here am merging the First colum values.


<head id="Head1" runat="server">
    <title>Copyright @ Fourthbottle</title>
<form id="form1" runat="server">
<table width="100%">
<td align="center">
<asp:GridView ID="grd_popup_details" runat="server" HeaderStyle-BackColor="LightBlue" AutoGenerateColumns="false" OnRowDataBound="grd_popup_details_RowDataBound">
<asp:BoundField HeaderText="Mobile Brand" ItemStyle-Width="90px" DataField="Brand" />
<asp:BoundField HeaderText="Model" ItemStyle-Width="90px" DataField="Model" />
<asp:BoundField HeaderText="Retail Price" ItemStyle-Width="90px" DataField="Price" />
<asp:BoundField HeaderText="Color" ItemStyle-Width="90px" DataField="Color" />


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace GRD_Merge_Paging
    public partial class MergeGrid : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
        protected void InitialBindingGrid()
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection("your Connection String");
            string Query1 = "select Brand,Model,Price,Color FROM Table1 order by Brand ";
            SqlDataAdapter da1 = new SqlDataAdapter(Query1, con);
            grd_popup_details.DataSource = dt;

      protected void grd_popup_details_RowDataBound(object sender, GridViewRowEventArgs e)
            int RowSpan = 2;
            for (int i = grd_popup_details.Rows.Count - 2; i >= 0; i--)
                GridViewRow currRow = grd_popup_details.Rows[i];
                GridViewRow prevRow = grd_popup_details.Rows[i + 1];
                if (currRow.Cells[0].Text == prevRow.Cells[0].Text)
                    currRow.Cells[0].RowSpan = RowSpan;
                    prevRow.Cells[0].Visible = false;
                    RowSpan += 1;
                    RowSpan = 2;