This example demonstrates how calculate total price in GridView Control.

First, you will need to import the System.Data.SqlClient namespace.

The System.Data.SqlClient namespace contains the SqlConnection and SqlCommand Classes that we need in order to operate database.In order to run this example correctly, please modify uid and pwd of the connectionstring with the uid and pwd of your database.

We use the GridView1_RowDataBound1 event to do the work.

We then call the GridView1_RowDataBound1 to calculate every price.

The event occurs when a data row is bound to data in a GridView control. The code as following:

The front end CalculateTotalPriceWithGridViewCsharp.aspx page looks something like this:

The flow for the code behind page is as follows:

[csharp]
using System; using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
private double runningTotal = 0;

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(“server=Localhost;database=pubs;uid=sa;pwd=1234;”);
SqlCommand myCommand = new SqlCommand(“SELECT title, price FROM Titles WHERE price > 0”, myConnection);
try
{
myConnection.Open();
this.GridView1.DataSource = myCommand.ExecuteReader();
this.GridView1.DataBind();
myConnection.Close();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.ToString());
}
}

private void CalcTotal(string _price)
{
try
{
runningTotal += Double.Parse(_price);
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.ToString());
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CalcTotal(e.Row.Cells[1].Text);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = “Total”;
e.Row.Cells[1].Text = string.Format(“{0:c}”,runningTotal);
}
}
}
[csharp]

Download Source Files