Reputation: 31
I am working with an application where user can multiply quantity and price and the results appear in third column using column expression The code i used is showed under this :
DataTable dt = new DataTable("dtList");
DataTable dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Decimal");
dc.ColumnName = "Price";
DataColumn dc1 = new DataColumn();
dc1.DataType = System.Type.GetType("System.Decimal");
dc1.ColumnName = "qty";
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.Decimal");
dc2.ColumnName = "Total";
dc2.Expression = "Price * qty";
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc1);
dataTable.Columns.Add(dc2);
object sumObject;
sumObject = dt.Compute("Sum(Total)", "");
I used this code to sum column Total, and show the result in a Text Box, but it's showing an error like this: "Cannot find column [Total]".
My question is what can i change, to make this code work, also sum automatically every time when the user change qty. Sorry for my English and mistakes at my code I am new to WPF
Upvotes: 0
Views: 711
Reputation: 784
Giving a fast check to your code I can see one thing.You define a DataTable called dt and then you try to compute the column "dt.Total" but you have never defined a column in you dt.
Try changing your:
sumObject = dt.Compute("Sum(Total)", "");
to
sumObject = dataTable.Compute("Sum(Total)", "");
Edit: By the way, if you do this:
dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Decimal");
dc.ColumnName = "Price";
DataColumn dc1 = new DataColumn();
dc1.DataType = System.Type.GetType("System.Decimal");
dc1.ColumnName = "qty";
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.Decimal");
dc2.ColumnName = "Total";
dc2.DefaultValue = 5;
dc2.Expression = "Price * qty";
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc1);
dataTable.Columns.Add(dc2);
Your third column already has the value "price * qty". If you want to show the sum of all your dc Total column just use:
object sumObject = dataTable.Compute("Sum(Total)", "");
And then
yourTextbox.Text = sumObject.ToString();
Upvotes: 1