Running Total In Gridview Footer In ASP.NET C# VB.NET

In this example i am going to demonstrate how to Display Running Total In GridView Footer Row In ASP.NET using C# and VB.NET. This method works with paging enabled gridview as well.

Running Total In Gridview Footer In ASP.NET

For demo purpose gridview is populated using sqldatasource having table with columns ID ,Name,Amount

I m showing total of amount column is gridview footer. for this we need to sum the the column in RowDataBound Even of Gridiew

Html source of gridview is
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False"
              DataKeyNames="ID" DataSourceID="SqlDataSource1" 
              OnRowDataBound="GridView1_RowDataBound" 
              ShowFooter="True" AllowPaging="True" PageSize="5" 
              BackColor="#ffffff" BorderColor="AliceBlue" 
              BorderStyle="None" BorderWidth="1px" 
              CellPadding="3" 
              CellSpacing="2" FooterStyle-BackColor="#da821e" 
              FooterStyle-ForeColor="#ffffff" 
              RowStyle-BackColor="#003366" 
              RowStyle-ForeColor="#ffffff" 
              AlternatingRowStyle-BackColor="#da821e">
<Columns>
     <asp:BoundField DataField="ID" HeaderText="ID" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="ID" />
     <asp:BoundField DataField="Name" HeaderText="Name" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="Name" FooterText="Total"/>
     <asp:TemplateField HeaderText="Amount">
     <ItemTemplate>
     <asp:Label ID="lblAmount" runat="server" 
                Text='<%# "$"+Eval("Amount").ToString()%>'>
     </asp:Label>
     </ItemTemplate>
     <FooterTemplate>
     <asp:Label ID="lblTotal" runat="server"></asp:Label>
     </FooterTemplate>
     </asp:TemplateField>
     </Columns>
     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
     <HeaderStyle BackColor="#da821e" Font-Bold="True" 
                  ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Amount] FROM [Expenses]">
</asp:SqlDataSource>
Now we need to write code for summing the column in RowdataBound Even of GridView

C# code behind
public partial class _Default : System.Web.UI.Page 
{
    decimal grdTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void GridView1_RowDataBound
                   (object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  decimal rowTotal = Convert.ToDecimal
              (DataBinder.Eval(e.Row.DataItem, "Amount"));
  grdTotal = grdTotal + rowTotal;
 }
 if (e.Row.RowType == DataControlRowType.Footer)
 {
  Label lbl = (Label)e.Row.FindControl("lblTotal");
  lbl.Text = grdTotal.ToString("c");
 }
}
}


VB.NET code behind
Public Partial Class _Default
    Inherits System.Web.UI.Page
    Private grdTotal As Decimal = 0
    Protected Sub Page_Load
    (ByVal sender As Object, ByVal e As EventArgs)
        
End Sub

Protected Sub GridView1_RowDataBound
(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowTotal As Decimal = 
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
grdTotal = grdTotal + rowTotal
End If

If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl
                           ("lblTotal"), Label)
lbl.Text = grdTotal.ToString("c")
End If
End Sub
End Class


Hope this helps

Other gridview articles:
Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Pouplating Multiple DetailsView based on single GridView using DataKeyNames

Merging GridView Headers to have multiple Headers in GridView

Search Records In GridView And Highlight Results Using AJAX ASP.NET

Insert update Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate

24 comments:

  1. Good collection

    see this blogs. I liked this blog, it has lots of
    nice articles

    http://aspnetcsharp4.blogspot.com/

    ReplyDelete
  2. This will not work for a paged gridview with more rows than the maximum per page. It can only show the total for the page. However, if the accumulator variable is only zeroed out in the
    !Page.IsPostBack then the totals can accumulate but only based on the pages selected so any value could be created for the total depending on the pages selected. Therefore, there is no way to get a running total in a paged gridview.

    ReplyDelete
  3. It was very interesting for me to read the post. Thank you for it. I like such themes and anything connected to this matter. I would like to read a bit more on that blog soon.

    ReplyDelete
  4. Can any1 tell me how to do running total with the Paging on couse in this solution Total gets 0 when page changes.....

    ReplyDelete
  5. plz....send download like........

    ReplyDelete
  6. Pretty interesting site you've got here. Thank you for it. I like such themes and anything that is connected to them. I would like to read more on that blog soon.

    Truly yours
    Alice Tudes

    ReplyDelete
  7. Hi sir,
    your blog is among the best blogs available around on net.
    today i came across a strange problem
    i have a datagrid with paging enabled in asp.net which have to be populated with huge data(above 10000) records.

    and i have to show in footer the record count on each page and total records present
    like
    1-50 of 10000
    51-100 of 10000

    i searched whole google in 2 days but couldn't found any solution for.
    so thought to ask you for that.

    please revert with your great expertise on the topic

    thanks & regards
    alok aggarwal
    alokagga@gmail.com

    ReplyDelete
  8. Awesome contribution, works excellent!

    Have a little request, i have 2 columns that have the sum in the footer, i need another one to make a substraction of the 2 columns.

    like this

    SumCol1=250 SumCol2=125 Balance=375

    Any ideas?

    ReplyDelete
  9. kalyan said
    counting no total no rows knowing
    label1.Text=GridView1.Rows.Count; how to count them when gridview created dynamically

    ReplyDelete
  10. jai matadi .. great tutorial dude ..

    i would like to use this code in VB.NET for projects coz i have made that sought of programme will it be possible .. plz let me know ..

    mitt

    ReplyDelete
  11. hello, how is everyone right here? I am a new comer to this amazing online community. Hope to get new buddies and discover something right here.

    ReplyDelete
  12. hi,
    its nice ..............

    ReplyDelete
  13. thanx for this code..................

    ReplyDelete
  14. 100% CORRECT! THANKS BRO (^^,)

    ReplyDelete
  15. Dear Friend
    I want to change currency symbol from $ to Rs.
    I am unable to change it from footer total.
    Please help.
    Thanks

    ReplyDelete
  16. @Above:

    Plz look for code mentioned bolow in html source of gridview.

    HeaderText="Amount"
    Text='<%# "$"+Eval("Amount").ToString()%>'

    Now change the $ sign to whatever you like.

    ReplyDelete
  17. It is not working in my project.. all field are show but not add show as below

    100
    140
    120

    in footer Total 100140120

    please help me..........!

    ReplyDelete
  18. @Sunder: Have you written grdTotal = grdTotal + rowTotal; in rowDataBound And convert it to decimal ?

    decimal rowTotal = Convert.ToDecimal
    14
    (DataBinder.Eval(e.Row.DataItem, "Amount"));

    Your values are not converted to decimal so are getting append because of string type

    ReplyDelete
  19. Thank you very much for the code

    ReplyDelete
  20. I get no errors, which is fabulous, because all of the other examples I have found create pages and pages of errors. Sadly, I do not get a Total Either.

    The GridView:
    As above in example.











    The Code Behind it:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;


    namespace AudioNET
    {
    public partial class DemoInvStockVal : System.Web.UI.Page
    {
    decimal grdTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    decimal rowTotal = Convert.ToDecimal
    (DataBinder.Eval(e.Row.DataItem, "VALUE"));
    grdTotal = grdTotal + rowTotal;
    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
    Label lbl = (Label)e.Row.FindControl("lblTotal");
    lbl.Text = grdTotal.ToString("c");
    }
    }
    }
    }

    ReplyDelete
  21. Narayana said: it is very helpful but i want to write a code in gridview footer button.. please help me.. how can give action to gridview footer button.

    ReplyDelete
  22. @Above: plz refer Insert Edit Delete In GridView to know how to add button in gridview footer

    ReplyDelete
  23. i want full total at the end of each paging,no need of running pages column total,that is my problem..

    ReplyDelete