Try this example to Merge Repeated Cells in Gridview
1- Open VS and create a new website and add new Web Page and from ToolBox add Gridview Control and Bind it using SQLDayaSource so the page will be like this :-
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" CellPadding="4" Height="119px" DataSourceID="SqlDataSource1"
OnDataBound="GridView1_DataBound" ForeColor="#333333">
<Columns>
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
<asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City] FROM [Details] ORDER BY [State]"></asp:SqlDataSource>
</div>and in code behind we will add some code to Merge repeated cells in Gridview Controlprotected void GridView1_DataBound(object sender, EventArgs e)
{
for (int rowIndex = GridView1.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow gvRow = GridView1.Rows[rowIndex];
GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
for (int cellCount = 0; cellCount < gvRow.Cells.Count; cellCount++)
{
if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
{
if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
{
gvRow.Cells[cellCount].RowSpan = 2;
}
else
{
gvRow.Cells[cellCount].RowSpan = gvPreviousRow.Cells[cellCount].RowSpan + 1;
}
gvPreviousRow.Cells[cellCount].Visible = false;
}
}
}
}after that run your website and you will see the result will be like the below image
Sharing is Caring,
Danish Kharadi.
No comments:
Post a Comment