Reputation: 315
I need to set a column's value in a datatable as the sum of other two columns in a datatable.I tried expression column and is working fine . But the problem is that the value of expression column is not getting updated always.Suppose A,B are two columns in the datatable and the sum of these two columns should be shown in Column 'C'.When when the value of B is changed then the value of columns 'C' is also getting changed.But not when column 'A' is changed
DataTable dt1 = new DataTable();
dt1.Columns.Add("A", typeof(decimal));
dt1.Columns.Add("B", typeof(decimal));
dt1.Columns.Add("C", typeof(decimal), "A+B");
myGridView.Datasource = dt1;
Upvotes: 0
Views: 1946
Reputation: 2176
Should go like this:
DataTable dt1 = new DataTable();
dt1.Columns.Add("A", typeof(decimal));
dt1.Columns.Add("B", typeof(decimal));
dt1.Columns.Add("C", typeof(decimal));
foreach (DataRow dr in dt1.Rows)
{
dr[2] = Convert.ToDecimal(dr[0]) + Convert.ToDecimal(dr[1]);
}
myGridView.Datasource = dt1;
Upvotes: 0
Reputation: 9725
This is an educated guess without seeing your code but it seems as though if you are using Compute then you quite possibly shouldn't use an expression column for this, rather you should use a DataColumn... Taken from here
"If you must perform an operation on two or more columns, you should create a DataColumn, set its Expression property to an appropriate expression, and use an aggregate expression on the resulting column. In that case, given a DataColumn with the name "total", and the Expression property set to this: "Quantity * UnitPrice"
Upvotes: 1