FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach

I decided to write this post because I always encounter this kind of issue so many times before at the forums. The main question is that they want to automatically calculate the totals when a user enter an amount from the TextBox control that is residing in the GridView template. So this example shows the basic way on how to achieve this with the server side manipulations.

Note that this demo requires that you know the basics of ADO.NET and for binding a GridView control with data from database.

Here are the code blocks below:

Assuming that we have this GridView mark up below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true"> <Columns> <asp:BoundField DataField="ItemDescription" HeaderText="Item"/> <asp:TemplateField HeaderText="Amount"> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged">
</asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>

Note: Be sure to set ShowFooter to TRUE so that the footer will show when the GridView is rendered in the page.

The following are the code blocks for binding the GridView with data from database:

private string GetConnectionString(){ //Where MYDBConnection is the connetion string that was set up in the web config file return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString; }

// Method for Binding the GridView Control private void BindGridView(){ SqlConnection connection = new SqlConnection(GetConnectionString()); try { connection.Open(); string sqlStatement = "SELECT * FROM TableName"; SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlDa.Fill(dt); if (dt.Rows.Count > 0) { GridView1.DataSource = dt; GridView1.DataBind(); } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Fetch Error:"; msg += ex.Message; throw new Exception(msg); } finally { connection.Close(); } }

protected void Page_Load(object sender, EventArgs e){ if (!Page.IsPostBack) { BindGridView(); //Bind GridView on initial postabcks } }

And here’s the code block for calculating the Totals:

//Calculate the Totals in the TextBox rows protected void TextBox1_TextChanged(object sender, EventArgs e){ double total = 0; foreach (GridViewRow gvr in GridView1.Rows) { TextBox tb = (TextBox)gvr.Cells[1].FindControl("TextBox1"); double sum; if(double.TryParse(tb.Text.Trim(),out sum)) { total += sum; } } //Display the Totals in the Footer row GridView1.FooterRow.Cells[1].Text = total.ToString(); }

Note:

Be sure to set AutoPostBack to TRUE for your TextBox control so that the TextChanged event will fire up.

That’s it! Hope you will find this example useful!

This article is part of the GWB Archives. Original Author: Vincent Maverick Durano

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.