c# - Updating SUM when cell value change in DataTable -
i'm having problem c# code. i'm trying add new row datatable , calculate things , insert specific cells.
here i'v got :
object sumamount; object sumdest; object sumwhole; datarow row = datatable.newrow(); row["number"] = "1"; datatable.rows.add(row); sumamount = datatable.compute("sum(amount)", ""); datatable.rows[datatable.rows.count - 1][all] = int32.parse(sumamount.tostring()); sumdest = datatable.compute("sum(dest)", ""); datatable.rows[datatable.rows.count - 1][columnnumber] = int32.parse(sumdest.tostring()); sumwhole = datatable.compute("sum(wholeamount)", ""); datatable.rows[datatable.rows.count - 1][alltogether] = int32.parse(sumwhole.tostring());
it works correctly first time. when change cell value i'm recalculating this same code (part datatable =) , when i'm doing cell value isnt replaced, added.
example:
when had :
10 3 13 6 1 7 2 0 2 18 4 22 << sum
and insert 1 in cell in 2nd column im expecting :
10 3 13 6 1 7 2 1 3 18 5 23
but im getting :
10 3 13 6 1 7 2 1 3 38 9 45
as can see these values being added, don't why? can me finding bug in code?
its not spreadsheet, doesnt know exclude last row formula. looks 3rd column total? if so, that can expression datatable
maintains:
dtxyz = new datatable(); dtxyz.columns.add("x", typeof(int32)); dtxyz.columns.add("y", typeof(int32)); dtxyz.columns.add("z", typeof(int32)); dtxyz.columns["z"].expression="x+y";
the columns typed x+y
adds. add data are:
dtxyz.rows.add(new object[]{10, 3}); dtxyz.rows.add(new object[]{6, 1}); dtxyz.rows.add(new object[]{2, 0}); dtxyz.rows.add(dtxyz.compute("sum(x)", ""), dtxyz.compute("sum(y)", ""));
the last column need computed, expression
take care of that. 1 way use compute
, not include grand total row, remove , readd each time:
int nrows = dtxyz.rows.count - 1; dtxyz.rows.removeat(nrows); dtxyz.rows.add( dtxyz.compute("sum(x)", ""), dtxyz.compute("sum(y)", ""));
but rather doing able use compute
, can summing extension methods , post new value:
int nrows = dtxyz.rows.count - 1; dtxyz.rows[nrows ]["x"] = dtxyz.asenumerable() .take(nrows) .sum(x => x.field<int>("x")); dtxyz.rows[nrows ]["y"] = dtxyz.asenumerable() .take(nrows) .sum(x => x.field<int>("y"));
or loop work. either way, remember dont have fiddle last column if based on expression
- in fact cant.
Comments
Post a Comment