There are two options.
Option1
The
Expression
property of
DataColumn
explained here
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.90).aspx[
^] can be used to establish the relation of
Total = Quantity * Price
for the
Total
column as shown below, in which case the
Total
field will be a
read only
field.
DataTable products = new DataTable("Products");
products.Columns.Add("IdProduct",typeof(int),null);
products.Columns.Add("Quantity",typeof(double),null);
products.Columns.Add("Price",typeof(double),null);
products.Columns.Add("Total",typeof(double),"Price * Quantity");
products.Rows.Add(1, 5, 25.5);
products.Rows.Add(2,10,37.7);
float TotalOrder = float.Parse(products.Compute("sum(Total)",string.Empty).ToString());
Console.WriteLine (TotalOrder);
Option 2
LINQ
can be used as follows to calculate
Total
for each
Row
DataTable products = new DataTable("Products");
products.Columns.Add("IdProduct",typeof(int),null);
products.Columns.Add("Quantity",typeof(double),null);
products.Columns.Add("Price",typeof(double),null);
products.Columns.Add("Total",typeof(double),null);
products.Rows.Add(1, 5, 25.5);
products.Rows.Add(2,10,37.7);
products.AsEnumerable().Select ( p => { p.SetField<double>("Total",
p.Field<double>("Quantity") * p.Field<double>("Price"));
return p;
}).Count ();
float TotalOrder = float.Parse(products.Compute("sum(Total)",string.Empty).ToString());
Console.WriteLine (TotalOrder);