Home > ASP.Net > Merge Repeated Cells in Gridview

Merge Repeated Cells in Gridview

Hi all,

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 :-

    <asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns="False" CellPadding="4" Height="119px" DataSourceID="SqlDataSource1"        
OnDataBound="GridView1_DataBound" ForeColor="#333333">
            <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        <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:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT [Country], [State], [City] FROM [Details] ORDER BY [State]"></asp:SqlDataSource>

and in code behind we will add some code to Merge repeated cells in Gridview Control

protected 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;
                        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

Hope this helps

Good Luck

Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: