Part - 9Imagine that we want to display a column total at the bottom of a column. In that case, we can handle the GridView RowDataBound event to sum the values in a column and display the summary in the column footer. For example, in the page given below contains a GridView control that displays a summary column representing the total marks obtained by all students.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private TotalMarks As Decimal = 0
Protected Sub TotalMarks_RowDataBound(ByVal sender As Object, ByVal e AsGridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Totals As Decimal = CType(DataBinder.Eval(e.Row.DataItem, "TOTAL_MARKS"),Decimal)
TotalMarks += Totals
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lblTotalMarks As Label = CType(e.Row.FindControl("lblTotal"), Label)
lblTotalMarks.Text = String.Format("Total=" & TotalMarks)
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
</style>
</head>
<body>
<form id="form1" runat="server" >
<asp:GridView
id="GridView1"
DataSourceID="SqlDataSource1"
OnRowDataBound="TotalMarks_RowDataBound"
AutoGenerateColumns="false"
ShowFooter="true"
Runat="server" Width="287px">
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID" />
<asp:BoundField
DataField="NAME"
HeaderText="NAME" />
<asp:TemplateField HeaderText="Total_Marks">
<ItemTemplate>
<%# Eval("TOTAL_MARKS")%>
</ItemTemplate>
<FooterTemplate>
<asp:Label
id="lblTotal"
Runat="server" Font-Bold="true" BackColor="Brown"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT [ID], [NAME], [TOTAL_MARKS] FROM [MARKSHEET]">
</asp:SqlDataSource>
</form>
</body>
</html>
Notice that the GridView control uses a TemplateField to represent the MARKS_TOTAL column. The TemplateField includes a <FooterTemplate> that contains a Label control. The TotalMarks_RowDataBound() method displays the total of the marks in this Label control.
HAVE A GREAT CODING!