Venkat Venkat - 11 days ago 11
C# Question

add sum of the rows in each column in data grid bind to datasource

i have dynamic columns in datagrid which bind to datasource.Now i want to add sum of the each column as a last row to the each column my code is

DataTable dt = dgvReport.DataSource as DataTable;
DataRow row = dt.NewRow();
dt.Rows.Add(row);
row[0] = "Totals";
for (int i = 1; i < dgvReport.Columns.Count; i++)
{
int sum = 0;
for (int j = 1; j < dgvReport.Rows.Count; ++j)
{
sum += Convert.ToInt32(dgvReport.Rows[j].Cells[i].Value.ToString());
}
}


but it is not working.I need for each column

15

10

30



55

Answer

You're summing all rows, including "Total" row that has no value. And don't need to use ToString() and then cast as integer.

According to your loop, I assume Colum[0] and Row[0] has the captions of your table.

|------|-------|------|------|
|      | Cap1  | Cap2 | Cap3 |
|------|-------|------|------|
| Cap1 |  10   |  20  |  10  |
|------|-------|------|------|
| Cap2 |  15   |  10  |  13  |
|------|-------|------|------|
|Totals|  25   |  30  |  23  |
|------|-------|------|------|

DataTable dt = dgvReport.DataSource as DataTable;
DataRow row = dt.NewRow();
dt.Rows.Add(row);
row[0] = "Totals";

for (int i = 1; i < dgvReport.Columns.Count; i++)
{
    int sum = 0;
    for (int j = ; j < dgvReport.Rows.Count; ++j)
    {
        if ( j < dgvReport.Rows.Count - 1)
            sum += Convert.ToInt32(dgvReport.Rows[j].Cells[i].Value);
        else
            dgvReport.Rows[j].Cells[i].Value = sum;
    }
}