Hivarun.p,
Check this example. Now please take its reference and correct your code.
I have created the example using the below article.
HTML
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound" Caption="All Records">
<Columns>
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="ContactName" HeaderText="Name" />
</Columns>
</asp:GridView>
</td>
<td> </td>
<td>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Caption="Merged Records">
<Columns>
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="ContactName" HeaderText="Name" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<br />
<asp:Button Text="Get Merged" runat="server" OnClick="GetValue" />
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
GridView1.DataSource = GetData("SELECT TOP 9 ContactName, Country, City FROM Customers GROUP BY Country, City, ContactName");
GridView1.DataBind();
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void OnDataBound(object sender, EventArgs e)
{
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
for (int j = 0; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
}
}
}
protected void GetValue(object sender, EventArgs e)
{
DataTable dt = GetData("SELECT TOP 1 ContactName, Country, City FROM Customers").Clone();
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < GridView1.Columns.Count; i++)
{
string contactName = "";
string country = "";
string city = "";
if (row.Cells[i].RowSpan > 0)
{
country = row.Cells[0].Text;
city = row.Cells[1].Text;
contactName = row.Cells[2].Text;
dt.Rows.Add(contactName, country, city);
break;
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
}
Screenshot