Girish Nebhinani
Girish Nebhinani

Reputation: 11

how to calculate the sum of the datatable-columns in vb.net

I have a DataTable which has 7 columns:

  1. Form No
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. Total

The DataTable contains 5 rows.

I want to show the sum of the Column-2 (that have Name 1) to Column-6 (that have Name 5) in column-7 (that have Name Total)

What is the best way of doing this?

Upvotes: 0

Views: 2396

Answers (1)

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can loop through rows and get sum. Like this.

int total = 0;
for (int y = 0; y < dt.Rows.Count; y++)
{
    string val = dt.Rows[y][1].ToString();
    int ival = 0;
    if(int.TryParse(val,out ival))
    {
        total = total + ival;
    }

}
int rowcount = dt.Rows.Count;
dt.Rows[rowcount - 1][1] = total;

Upvotes: 1

Related Questions