Hi akhter,
Use the OnRowDataBound event to calculate the Total and display in the footer.
Refer below sample.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true"
OnRowDataBound="GridView1_OnRowDataBound">
<Columns>
<asp:BoundField DataField="ItemName" HeaderText="ItemName" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label Text='<%#Eval("Price") %>' ID="lblPrice" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:Label Text='<%#Eval("Total") %>' ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("ItemName", typeof(string)), new DataColumn("Price", typeof(decimal)) });
dt.Rows.Add("A", 10);
dt.Rows.Add("B", -20);
dt.Rows.Add("C", 5);
dt.Rows.Add("D", -10);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
decimal total = 0;
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblPrice = (e.Row.FindControl("lblPrice") as Label);
total += Convert.ToDecimal(lblPrice.Text);
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblTotal = (e.Row.FindControl("lblTotal") as Label);
lblTotal.Text = "Total : " + total.ToString();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("ItemName", GetType(String)), New DataColumn("Price", GetType(Decimal))})
dt.Rows.Add("A", 10)
dt.Rows.Add("B", -20)
dt.Rows.Add("C", 5)
dt.Rows.Add("D", -10)
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Private total As Decimal = 0
Protected Sub GridView1_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblPrice As Label = (TryCast(e.Row.FindControl("lblPrice"), Label))
total += Convert.ToDecimal(lblPrice.Text)
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lblTotal As Label = (TryCast(e.Row.FindControl("lblTotal"), Label))
lblTotal.Text = "Total : " & total.ToString()
End If
End Sub
Screenshot