troubleshooting Question

DataTable row summation

Avatar of cso2013
cso2013 asked on
.NET ProgrammingVisual C++.NETMicrosoft Development
5 Comments1 Solution875 ViewsLast Modified:
I have been tasked with something I thought would be relatively simple. I have a datatable that I am creating from an Excel Spreadsheet. I can sum each column and add a row for the column totals. However (I've been at this for a week), I can't figure out how to sum the rows horizontally.

I've tried looping through and adding each column and posting it in the additional column (which appears when I run it). The furthest I can get is to an "invalid cast exception" --

This is the code that I am trying to use. It works fine if you are using a self-made datatable, but throws the invalid cast  -- I am using C#.

  int sum = 0;
   foreach (DataRow rows in dt.Rows)
        for (int i = 0; i < dt.Columns.Count; i++)
            for (int j = 0; j < dt.Rows.Count; j++)

                int number = Convert.ToInt32(dt.Rows[j].Field<int>(i));
                sum += number;

              rows["testrow"] = sum;
            dataGridView1.DataSource = dt;
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros