14,327,634 members
Rate this:
See more:
Hy,

here's the problem. I got a table and what I want to do is to make a sum, but only for a single person in that table, not all of them. etc.

Table

ID FirstName FamilyName Amount

------------------------------------------------------------------------------

1 John Smith 500

1 John Smith 250

2 Alison White 1000

2

3 Andrew Kazinsky 300

``` decimal zbroj = 0;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[5];
{
if (cell.Value != null)
{
zbroj += Convert.ToDecimal(cell.Value);
}
}
}
tbIznosBrutoDodatkaOdbitka.Text = zbroj.ToString();
```

I get a sum of 2050, and what I need is to get 750 (only for John Smith).

If I haven't make myself clear enough, I do not need sum only for John Smith, but for everyone, even if that person is placed in multiple rows.

Thx for any help.
Posted
Updated 3-Oct-11 1:10am
v2

Rate this:

## Solution 1

```decimal zbroj = 0;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[5];
{
if (cell.Value != null && row.Cells[4].Value=="John Smith")
{
zbroj += Convert.ToDecimal(cell.Value);
}
}
}
tbIznosBrutoDodatkaOdbitka.Text = zbroj.ToString();```

hzawary 3-Oct-11 7:12am

My 4, I want to write this, only in */row.Cells[4].Value=="John Smith"/* must changed to */row.Cells[3].Value.ToString()+row.Cells[4].Value.ToString()=="John Smith"/*
Rate this:

## Solution 2

You can write some logic in your loop above to do that (for e.g. store the name in a dictionary and then check against the key). If the key exists, total against the value of the dictionary.

However, it would just be easier to run a Group By and Sum query on the database.
Rate this:

## Solution 3

to get sum of column of a grid ...

```double total_amt = 0;
for (int r = 0; r < grd_bill_master.Rows.Count - 1; r++)
{
//if (!Convert.ToDouble(grd_bill_master.Rows[r].Cells[15].Value))
//{
total_amt = total_amt + Convert.ToDouble(grd_bill_master.Rows[r].Cells[15].Value);
//}
}
txt_total_amount.Text = total_amt.ToString();```
Davor Bursac 3-Oct-11 8:59am

Hy,
my question wasn't put correctly, I don't need sum of a whole column, but only of those cells in a column which have same ID. e.g. i have a grid with 3 people, each of them takes 2 rows (so, 6 rows in total). What I want is, when I click on one of them, to get a sum of 2 cells, but just for that person. And if I click on another person, to get sum of his 2 cells.
Thx.