How to get GridView Running Column Sub Total in ASP.NET

This article shows how to get a GridView's current page row column total of a sum and the GridView's all rows column grand total of the sum.

Step 1: Database

First create a table in a database as in the following.

Table: Item

  1. create table Item   
  2. (  
  3. Itemid int identity(1, 1) primary key,  
  4. ItemName varchar(100),  
  5. ItemPrice decimal(7, 2)  
  6. )  
Now fill in some records in a database as in the following:



Figure 1: Table Record

Step 2: Visual Studio
  1. Add a new project.
  2. Go to the project in Solution Explorer.
  3. Right-click and Add Item.
  4. Select Web Form as in the following.



Figure 2: Add Form

Step 3: UI Design

In this Design section add a GridView control to display the database table data on a web page.

UI Design

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Master/Master.master" AutoEventWireup="true" CodeFile="Gridviewsum.aspx.cs" Inherits="UI_Gridviewsum" %>  
  2.   
  3. <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">  
  4. </asp:Content>  
  5. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">  
  6.     <h2 style="color: #00CC00">Gridview Column Total and Sub Total</h2>  
  7.     <div>  
  8.         <asp:GridView ID="GridItem" runat="server" Width="100%"   
  9.                 AutoGenerateColumns="False"  
  10.                 RowStyle-HorizontalAlign="Center"   
  11.                 ShowFooter="True" AllowPaging="True" PageSize="5" OnPageIndexChanging="GridItem_PageIndexChanging" OnRowDataBound="GridItem_RowDataBound"   
  12.                 BackColor ="White" BorderColor="#CC9966"  BorderWidth="1px" CellPadding="4"  >  
  13.               
  14.                 <Columns>  
  15.                     <asp:TemplateField HeaderText="Item No">  
  16.                         <ItemTemplate><%#Eval("Itemid")%></ItemTemplate>  
  17.                     </asp:TemplateField>  
  18.                       
  19.                     <asp:TemplateField HeaderText="Item Name">  
  20.                         <ItemTemplate><%#Eval("ItemName")%></ItemTemplate>  
  21.   
  22.                         <FooterTemplate>  
  23.                             <div style="padding:0 0 5px 0"><asp:Label Text="Page Total" runat="server" /></div>  
  24.                             <div><asp:Label Text="Grand Total" runat="server" /></div>  
  25.                         </FooterTemplate>  
  26.   
  27.                     </asp:TemplateField>  
  28.                       
  29.                     <asp:TemplateField HeaderText="Price ">  
  30.                         <ItemTemplate><asp:Label ID="lblPrice" runat="server" Text='<%#Eval("ItemPrice")%>'>  
  31.                             </asp:Label></ItemTemplate>  
  32.   
  33.                         <FooterTemplate>  
  34.                             <div style="padding:0 0 5px 0"><asp:Label ID="lblTotal" runat="server" /></div>  
  35.                             <div><asp:Label ID="lblTotalPrice" runat="server" /></div>  
  36.                         </FooterTemplate>  
  37.   
  38.                     </asp:TemplateField>  
  39.                 </Columns>  
  40.                 <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />  
  41.                 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />  
  42.                 <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />  
  43.                 <RowStyle BackColor="White" ForeColor="#330099" />  
  44.                 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />  
  45.                 <SortedAscendingCellStyle BackColor="#FEFCEB" />  
  46.                 <SortedAscendingHeaderStyle BackColor="#AF0101" />  
  47.                 <SortedDescendingCellStyle BackColor="#F6F0C0" />  
  48.                 <SortedDescendingHeaderStyle BackColor="#7E0000" />  
  49.             </asp:GridView>  
  50.     </div>  
  51. </asp:Content>  
Step 4: UI Code

In this code section we will write the GridView bind code and add a GridView page index changing command and row data bound command as in the following from the GridView properties.



Figure 3: Add Command

Also add a viewstate for the store item price.

UI CODE
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10.   
  11. public partial class UI_Gridviewsum: System.Web.UI.Page {  
  12.     string connection = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;  
  13.     protected void Page_Load(object sender, EventArgs e) {  
  14.         if (!IsPostBack) {  
  15.             BindItemList();  
  16.         }  
  17.     }  
  18.     private void BindItemList() {  
  19.         string Query = "SELECT * FROM Item";  
  20.         using(SqlConnection con = new SqlConnection(connection)) {  
  21.             using(SqlCommand cmd = con.CreateCommand()) {  
  22.                 cmd.CommandText = Query;  
  23.                 con.Open();  
  24.                 DataTable dt = new DataTable();  
  25.                 SqlDataAdapter da = new SqlDataAdapter();  
  26.                 da.SelectCommand = cmd;  
  27.                 da.Fill(dt);  
  28.   
  29.                 if (ViewState["TotalPrice"] == null) {  
  30.                     Decimal Price = 0;  
  31.                     for (int i = 0; i <= dt.Rows.Count - 1; i++) {  
  32.                         Price += dt.Rows[i].Field < Decimal > (2);  
  33.                     }  
  34.                     ViewState["TotalPrice"] = Price;  
  35.                 }  
  36.                 GridItem.DataSource = dt;  
  37.                 GridItem.DataBind();  
  38.             }  
  39.         }  
  40.     }  
  41.     protected void GridItem_PageIndexChanging(object sender, GridViewPageEventArgs e) {  
  42.         GridItem.PageIndex = e.NewPageIndex;  
  43.         BindItemList();  
  44.     }  
  45.     Decimal Page_Sum;  
  46.     protected void GridItem_RowDataBound(object sender, GridViewRowEventArgs e) {  
  47.         if (e.Row.RowType == DataControlRowType.DataRow) {  
  48.             Label lblPageTotal = (Label) e.Row.FindControl("lblPrice");  
  49.             Page_Sum += Decimal.Parse(lblPageTotal.Text);  
  50.         }  
  51.         if (e.Row.RowType == DataControlRowType.Footer) {  
  52.             if (ViewState["TotalPrice"] != null && Page_Sum != 0) {  
  53.                 Label lblTotal = (Label) e.Row.FindControl("lblTotal");  
  54.                 lblTotal.Text = Page_Sum.ToString();  
  55.   
  56.                 Label lblTotalPrice = (Label) e.Row.FindControl("lblTotalPrice");  
  57.                 lblTotalPrice.Text = ViewState["TotalPrice"].ToString();  
  58.             }  
  59.         }  
  60.     }  
  61. }  
Step 5: Browser

Now your page is ready to run in a browser, press F5.



Figure 4: Grid Page 1 Sub Total and Grand Total



Figure 5: Grid Page 2 Sub Total and Grand Total

I hope you understand how to get a running item price subtotal and total using an ASP.Net GridView control.

Up Next
    Ebook Download
    View all
    Learn
    View all