If you want to display the Total in the footer of a gridview. Follow the steps:

1) Create a table of employees with salary.

2) Select ename,esalary from emptbl

ename esalary

Bharath 18000

krishna 20000

3) Now in gridview the total of salary must come in footer.

4) .aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="ename" HeaderText="ename" SortExpression="ename" />
<asp:TemplateField HeaderText="esalary" SortExpression="esalary">

<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("esalary") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>

<asp:Label ID="Label2" runat="server" ></asp:Label>

</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>

</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT [ename], [esalary] FROM [emptbl]"></asp:SqlDataSource>
</form>
</body>
</html>


5) Code behind:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{

private int Total = 0;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

//DataBinder.Eval method Evaluates data-binding expressions at run time.

int Tot=(int)DataBinder.Eval(e.Row.DataItem,"esalary");
Total = Total + Tot;
}

if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbltotal = e.Row.FindControl("Label2") as Label;
lbltotal.Text = Total.ToString();
}
}
}

Any doubts mail me.

Advertisement