Reputation: 2603
I have a DataTable in C#, where I have a monthly report Like this:
I have just shown 4 dates as of now. All these date come from a PIVOT Table in SQL. Whereas, I have added the Totals column programmatically.
What I want is I want to count the number of A's, B's, and C's in Total A's, Total B's, and Total C's Field.
This is what I tried so far
DataTable report = DataAccess.GetDataInDataTable(ConstantFieldsModel.PRIMARYCONNECTION, "usp_GetReport", CommandType.StoredProcedure, param);
report.Columns.Add("Total As", typeof(int)).SetOrdinal(2);// adds 'Total' field at position 5
report.Columns.Add("Total Bs", typeof(int)).SetOrdinal(3);
report.Columns.Add("Total Cs", typeof(int)).SetOrdinal(4);
foreach (DataRow row in report.Rows)
{
int sum = 0;
foreach (DataColumn col in report.Columns)
{
if (!row.IsNull(col))
{
string val = row[col].ToString();
int a;
if (int.TryParse(val, out a))
{
sum += a;
}
}
}
row.SetField("Total", sum);
}
I get no errors, but the Total shows the Ids of each record which is NOT what I want. (I know the Total Field is at the beginning, but this is because I have a month report to avoid scrolling just to see the total, I have added it in the front.)
Any help would be appreciated.
Upvotes: 1
Views: 243
Reputation: 1063015
I have added the Totals column programmatically.
So: keep hold of these columns you have added:
List<DataColumn> myTotals = new List<DataColumn>();\
// and .Add when you create each column
Now, instead of looking at all columns:
foreach (DataColumn col in report.Columns)
just look at these 3
foreach (DataColumn col in myTotals)
If you declared them as being of type int
, you can probably avoid a format/parse step, too:
sum += (int)row[col];
Upvotes: 1