Search Asp.Net Here

How to Merge Cells or rows in GridView Control





Merging Cells or rows in GridView Control


Many time in our application we want to merge the cell or row of GridView control for better user interface. The are many methods on internet to solve this problem but with long and complex code. Here I am giving a simple and easy to understand example of how we can merge cell ( Columns) of GridView Control in asp.net






In this example every row and cell of Gridview is being read, starting from the second last at the bottom, to the top row of GridView. If a cell value is matching with the value of the previous row (lower row) cell then the RowSpan is increased and making the lower cell invisible, and so on…

Following sqlserver table (tbdept) is used in the example

Here is code for .aspx page

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4"
onprerender="GridView1_PreRender" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:BoundField DataField="deptno" HeaderText="No." />
<asp:BoundField DataField="deptnam" HeaderText="Department" />
<asp:BoundField DataField="deptcity" HeaderText="City" />
<asp:BoundField DataField="deptcnt" HeaderText="Country" />
</Columns>
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
</asp:GridView>

Code for .cs file (Replace the Page_Load event with following code)


protected void Page_Load(object sender, EventArgs e)
{
gridbind();
}
protected void gridbind()
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from tbdept", "server=.;database=database1;uid=sa");
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
//reading grid view rows in decending order
for (int i = GridView1.Rows.Count - 2; i >= 0; i--)
{
GridViewRow cur_row = GridView1.Rows[i];
GridViewRow pre_Row = GridView1.Rows[i + 1];
//Looping throurgh each cell of current row and matching with previous row's cells
for (int j = 0; j < cur_row.Cells.Count; j++)
{
if (cur_row.Cells[j].Text == pre_Row.Cells[j].Text)
{
if (pre_Row.Cells[j].RowSpan < 2)
cur_row.Cells[j].RowSpan = 2;
else
cur_row.Cells[j].RowSpan = pre_Row.Cells[j].RowSpan+1;
pre_Row.Cells[j].Visible =false;
}
}
}
}

Comments :

1
Sheeba Florence said...
on 

Site Checking

Post a Comment