summing a datagrid column

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
 
E

Eric Cadwell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top