Merge cells in Asp.net Gridview Footer as per requirement

Here I will explain how to  merge cells in asp.net grid view Footer  as per requirement.
write code like as shown below in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>merger Footer programmatically as per requirement</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true" BackColor="#339966" >
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Label ID="lblEname" runat="server" Text='<%#Eval("First_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<ItemTemplate>
<asp:Label ID="lblsalary" runat="server" Text='<%#Eval("salary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


 After that write the following code in code behind
SqlConnection connection=
 newSqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
connection.Open();
SqlDataAdapter da = 
new SqlDataAdapter("SELECT * FROM dbo.Employee", connection);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DataSet ds = new DataSet();


SqlDataAdapter da = new SqlDataAdapter("SELECT Sum(salary) FROM dbo.Employee", connection);
// connection.Open();
da.Fill(ds);
e.Row.Cells[0].ColumnSpan = 3;
e.Row.Cells.RemoveAt(1);
e.Row.Cells.RemoveAt(2);
e.Row.Cells[0].Text = "<b>Total Payee Salary Of This Month:-</b>" + ds.Tables[0].Rows[0][0];
connection.Close();
}
}

Cells mergening logic are implemented in GridView1_RowDataBound 
as you see three cells are merged to show Employee total payee.

DEMO

Categories:

0 comments:

Post a Comment