Gold
Gold

Reputation: 62424

How does one sum a whole column of datagridview?

I have a Datagridview in my C# program that contain numeric data.

I need to sum all column A and all column B.

(I don't want to use any SQL queries.)

How Do I do this?

Thanks in advance.

Upvotes: 1

Views: 7428

Answers (2)

sh4
sh4

Reputation: 1265

If your Datagrid is bound to a DataTable, another option is to use the Datatable.Compute() method.

http://msdn.microsoft.com/es-es/library/system.data.datatable.compute%28VS.80%29.aspx

private void ComputeBySalesSalesID(DataSet dataSet)
{
// Presumes a DataTable named "Orders" that has a column named "Total."
DataTable table;
table = dataSet.Tables["Orders"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

Upvotes: 2

Jaroslav Jandek
Jaroslav Jandek

Reputation: 9563

Use gridView.DataSource. It can be either an IList Interface or an IListSource Interface which has a method GetList() that returns an IList. So you can basically run a summing method on it's members.

Or if you know the exact type in DataSource, you can aggregate the data using specific methods of the object in there (even use the Enumerable.Sum Method if possible).

or

decimal sum;
foreach (DataGridViewRow row in dataGridView.Rows)
{
  sum += (decimal)row[0].Value + (decimal)row[1].Value;
}

Upvotes: 1

Related Questions