Click here to Skip to main content
15,913,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello ..
i need to make a data table like that:

Subjects          old        new    diff
Sub_1             10         50     40
Sub_2             30         10     -20
total             40         60     20


this is a part of code

DataTable subjects = new DataTable();
    subjects.Columns.Add("Subjects");
    subjects.Columns.Add("old");
    subjects.Columns.Add("new");
    subjects.Columns.Add("diff");
subjects.Rows.Add("Sub_1", sub1.Old    , sub1.New    , (sub1.New - sub1.Old));
subjects.Rows.Add("Sub_2", sub2.Old    , sub2.New    , (sub2.New - sub2.Old));
subjects.Rows.Add("Total", .. total of above    .. , .. total of above    .., .. total of above  ..);


so i need to ask how to calculate the total value of last column ( Total) , and is there is any other way to calculate the 4th coulmn ( 3rdcol - 2 2nd col )
Posted

1 solution

Adding a calculated column which operates on the totals in the current row is easy: You don't have to do the math yourself, the table can do that for you:
C#
DataTable subjects = new DataTable();
subjects.Columns.Add("Subjects");
subjects.Columns.Add("old", typeof(int));
subjects.Columns.Add("new", typeof(int));
subjects.Columns.Add("diff", typeof(int), "new-old");
subjects.Rows.Add("Sub_1", 50, 60);
subjects.Rows.Add("Sub_2", 100, 46);

But there is no automatic way to generate a totals row AFAIK.
You can do it manually:
C#
subjects.Rows.Add("TOTAL", subjects.Compute("Sum(old)", ""), subjects.Compute("Sum(new)", ""), subjects.Compute("Sum(diff)", ""));
But that won;t update itself automaticaaly - you will have to re-run the Computes each time a cell changes or a row is added / deleted.
 
Share this answer
 
Comments
Dev_Fady... 15-Feb-15 7:40am    
thanks aloot OriginalGriff for your support this is working good but another question is that i need to ask you in my real project the "diff" is the 4th column and i have other columns after it so when i use this code subjects.Rows.Add("Sub_1", sub1.Old , sub1.New , ,value of col5); how to rewrite it ???
OriginalGriff 15-Feb-15 7:53am    
Use null for the computed column:

subjects.Rows.Add("Temp", 200, 300, null, "hello");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900