LogoASPAlliance: Articles, reviews, and samples for .NET Developers
CodeSnip: How to Display Sum Total in the Footer of the GridView Control
by Sushila Bowalekar Patel
Average Rating: 
Views (Total / Last 10 Days): 96424/ 87



In this article, we will see how to display the sum total of a column in the footer of the GridView control using Visual Studio 2005.

For the purpose of this article, we will use the Products Table from the Northwind Database and the GridView control for data binding. The GridView control will display the data and SqlDataSource is supplied in the web.config file as shown in Listing 1.

Listing 1

<add name="DummyDB"
  connectionString="Server=localhost;Integrated  Security=True;Database=NorthWind;Persist,
  Security Info=True" providerName="System.Data.SqlClient"/>

Our goal is to display the total of the column UnitPrice in the footer as shown in Figure 1.

Figure 1

By default, the GridView's Showfooter property is set to false. We'll change it to true. As we are calculating the field UnitPrice, we'll use TemplateField's ItemTemplate to display UnitPrice and FooterTemplate to display the total.

Listing 2: Display Sum Total in Footer of GridView Control

<asp:GridView ID="GridView1"
  ShowFooter="true" DataKeyNames="ProductId"
  AutoGenerateColumns="false" runat="server"
<asp:BoundField DataField="Productid" HeaderText="Product Id" />
<asp:BoundField DataField="ProductName" FooterText="Total" HeaderText="Product Name" />
<asp:TemplateField HeaderText="Unit Price" FooterStyle-Font-Bold="True">
  <%# GetUnitPrice(decimal.Parse(Eval("UnitPrice").ToString())).ToString("N2") %>
  <%# GetTotal().ToString("N2") %>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DummyDB %>"
SelectCommand="Select * from Products">

Finally, we'll use Helper functions named GetUnitPrice and GetTotal to display the UnitPrice in the ItemTemplate and Total in the FooterTemplate. For instance, for each row of the GridView, a price value is passed to the GetUnitPrice function returning variable Price.

Listing 3: Using Helper Functions

[Visual Basic .NET]

Dim TotalUnitPrice As Decimal = 0.0
Function GetUnitPrice(ByVal Price As DecimalAs Decimal
  TotalUnitPrice += Price
  Return Price
End Function
Function GetTotal() As Decimal
  Return TotalUnitPrice
End Function


decimal TotalUnitPrice;
decimal GetUnitPrice(decimal Price) 
  TotalUnitPrice += Price;
  return Price;
decimal GetTotal()
  return TotalUnitPrice;


[Download Sample]


In this article, you have learned how to display the sum total of a column in the footer of the GridView control with the help of an example.

Product Spotlight
Product Spotlight 

©Copyright 1998-2021  |  Page Processed at 2021-01-16 7:05:33 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search