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;