summing a datagrid column

  • Thread starter Thread starter Geraldine Hobley
  • Start date Start date
G

Geraldine Hobley

Hello,
I wish to find the sum of the values in a datagrid
and place the value in a text box.
I have a datagrid called dgorders and I want to sum
the third column "qty". Any ideas on how I can do this.

Thanx

Geri
 
Loop though all the rows and add the values up:

int total = 0;
DataTable dt = null;
DataSet ds = dgorders.DataSource as DataSet;
if (ds != null)
dt = ds.Tables["table name goes here if bound to a dataset"];
if (dt == null)
dt = dgorders.DataSource as DataTable;
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
total += int.Parse(dt.Rows["qty"].ToString());
}
}
return total;

If the field is already an int type you could directly cast it to int:
total += (int)(dt.Rows["qty"]);

HTH;
Eric Cadwell
http://www.origincontrols.com
 
Back
Top