Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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!

 

Posted on Monday, June 1, 2009 1:20 PM ADO.NET , ASP.NET , C# , Tips&Tricks , GridView | Back to top


Comments on this post: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Thanks for the answer. It worked for me, but when i placed the textbox in an update panel so that the postback does not refresh the page, the event did not fire. Please let me know how to do that??
Left by Jyoti Varma on Jun 02, 2010 1:38 PM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
This saved me hours/days!

Great code!!
Left by Patricia on Jul 30, 2010 7:51 AM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Great Code boss Very Helpful!!!!!!!!!!!
Left by neelima on Apr 16, 2011 6:13 PM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Great Code!! Thanks.
Left by Munirah Malik on Oct 13, 2011 11:59 AM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Thanks for such meaningful code, In detail you describe every things. Thanks again
Left by Muhammad Tousif Shahid on May 30, 2012 2:36 PM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Sorry I am very new to this and am having an issue with:

'dt' is not declared. It may be inaccessible due to its protection level.

How do I define dt?

Thank you so much and sorry
Left by Jeremy on Jun 07, 2012 7:42 PM

# re: FAQ: Calculate Totals in GridView and Display it in Footer - Server side approach
Requesting Gravatar...
Do you have solution to the Jyoti Varma? If the gridview was put inside the update panel, TextChanged event will not fired, but Page_Load event was fired. How to resolve this problem?
Left by Anthony on Jun 23, 2012 4:07 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net