DataTable distinctTable = dTable.DefaultView.ToTable(true,\"ITEM_NO\",\"ITEM_STOCK\");
DataTable dtSummerized = new DataTable(\"SummerizedResult\");
dtSummerized.Co
In my case the issue was with my query itself.
My query returned difference of two columns. Like, query="Select A,B,A-B from Table"
and I was performing sum on datatable using compute function as dt.Compute("Sum(A-B)","")
.
So, datatable was unable to compute the sum of A-B
column. I gave the difference column alias as query="Select A,B,(A-B) as AB from Table"
and dt.Compute("Sum(AB)","")
.
Thus, resolved the error.
The problem is exactly about your DataType of the column. If you have a row with dynamically added columns without DataType like that (it may be a result of a manual calculation or cross-tab query-like)
myTable.Columns.Add("AddedColumn");
You will probably face with the column conversion issue. Instead, If you change your add method with pointing DataType like below
myTable.Columns.Add("AddedColumn", typeof(System.Int32));
It will work I think. It's what I experienced & fixed before...
You want to write:
dTable.Compute("sum(CONVERT(ITEM_STOCK, 'System.Double'))",
"ITEM_NO='" + dRow["ITEM_NO"].ToString() + "'")
instead of:
dTable.Compute("sum(" + TotalItem + ")", "ITEM_NO="...
because it will translate to dTable.Compute("sum(value_of_TotalItem), "ITEM_NO="...
, value_of_TotalItem
is a double and is not a column name.
See DataTable.Compute
try this:
DataTable distinctTable = dTable.Clone();
dTable.Columns.Add("ITEM_STOCK_D", typeof(Decimal),
"CONVERT(ITEM_STOCK, 'System.Decimal')");
foreach (DataRow dRow in dTable.Rows)
{
String itemNo = dRow["ITEM_NO"].ToString();
if(distinctTable.Select(String.Format("ITEM_NO = '{0}'",itemNo)).Length == 0)
{
double totalStock = Convert.ToDouble(dTable.Compute("SUM(ITEM_STOCK_D)",
String.Format("ITEM_NO = '{0}'", itemNo)));
distinctTable.Rows.Add(itemNo, totalStock.ToString());
}
}
dTable.Columns.Remove("ITEM_STOCK_D");
You might try this:
dTable.Compute("sum([" + TotalItem + "])","");
I.e enclose your column name in square brackets [ ]
The idea is from this post.