In this article I will explain with an example, how to display
sum of Columns total (Grand Total) in
GridView Footer in
ASP.Net using C# and VB.Net.
The
GridView has
paging enabled and the sum of values of a particular column on each page will be displayed in the
GridView Footer Row as
Grand Total.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The
HTML Markup consists of:
GridView - For displaying data.
In order to implement
Paging in
GridView,
AllowPaging property is set to true and
OnPageIndexChanging event has been assigned.
The
GridView consists of three
BoundField columns.
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" ShowFooter="true">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="Order ID" ItemStyle-Width="60" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-Width="210" />
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="60" DataFormatString="{0:N2}"
ItemStyle-HorizontalAlign="Right" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Linq;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Linq
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Binding the GridView and calculating the Sum of Columns Total
Inside the Page_Load event handler, the BindGrid method is called.
Inside the BindGrid method, the Query gets records of Orders along with Products and their respective costs.
After that, the connection string is read from the
Web.Config file.
Then, the records are fetched from the
Customers Table of
SQL Server database using
SqlDataAdapter and copied to
DataTable object using
Fill method.
Finally, the
DataTable is assigned to the
DataSource property of
GridView and the
GridView is populated, then
Sum of the
Price column is calculated and displayed in the
Footer Row’s Cell as
Grand Total.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string sql = "SELECT TOP 30 OrderID,";
sql += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
sql += "(Quantity * UnitPrice) Price";
sql += " FROM [Order Details] details";
sql += " ORDER BY OrderID";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvProducts.DataSource = dt;
gvProducts.DataBind();
//Calculate Sum and display in Footer Row
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Price"));
gvProducts.FooterRow.Cells[1].Text = "Total";
gvProducts.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
gvProducts.FooterRow.Cells[2].Text = total.ToString("N2");
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT TOP 30 OrderID,"
sql += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,"
sql += "(Quantity * UnitPrice) Price"
sql += " FROM [Order Details] details"
sql += " ORDER BY OrderID"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sql)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
gvProducts.DataSource = dt
gvProducts.DataBind()
'Calculate Sum and display in Footer Row
Dim total As Decimal = dt.AsEnumerable().Sum(Function(row) row.Field(Of Decimal)("Price"))
gvProducts.FooterRow.Cells(1).Text = "Total"
gvProducts.FooterRow.Cells(1).HorizontalAlign = HorizontalAlign.Right
gvProducts.FooterRow.Cells(2).Text = total.ToString("N2")
End Using
End Using
End Using
End Using
End Sub
Implementing Paging in GridView
Inside the
OnPageIndexChanging event handler, the
PageIndex property of the
GridView is set with the new
PageIndex and the
BindGrid method is called.
C#
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
gvProducts.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Screenshot
Demo
Downloads