Hi phonghue,
You have not assigned gvEmp_RowDataBound event handler to the GridView in ASPX page.
Refer the example.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2"
ForeColor="#0099FF" ShowFooter="True" GridLines="None" OnRowDataBound="OnRowDataBound">
<AlternatingRowStyle BackColor="#CCCCFF" />
<FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" />
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Tracks" SortExpression="ProductName">
<HeaderStyle ForeColor="Black" />
<ItemStyle ForeColor="Black" Width="250px" />
</asp:BoundField>
<asp:BoundField DataField="QuantityPerUnit" HeaderText="Total Each Track" ReadOnly="True" SortExpression="QuantityPerUnit">
<HeaderStyle ForeColor="Black" Font-Bold="True" />
<ItemStyle ForeColor="Black" />
</asp:BoundField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Eval("UnitPrice")%>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<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:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT TOP 5 * FROM [Products]"></asp:SqlDataSource>
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
GridView2.FooterRow.Cells[0].Text = string.Format("Total Records: {0}", GridView2.Rows.Count);
}
int total = 0;
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
total = total + Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitPrice"));
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblamount = e.Row.FindControl("lblTotal") as Label;
lblamount.Text = total.ToString();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
GridView2.FooterRow.Cells(0).Text = String.Format("Total Records: {0}", GridView2.Rows.Count)
End Sub
Private total As Integer = 0
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
total = total + Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitPrice"))
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lblamount As Label = TryCast(e.Row.FindControl("lblTotal"), Label)
lblamount.Text = total.ToString()
End If
End Sub
Screenshot