在列中执行计算SUM()时出错

时间:2019-05-05 13:46:25

标签: c# wpf datatable wpfdatagrid

我试图在datagrid中计算一列,我将在下面的代码中显示这些列。我不断收到这些错误。

我已经浏览了这些链接
1. How To Convert The DataTable Column type?
2. Error while taking SUM() of column in datatable
3. Invalid usage of aggregate function Sum() and Type: String

M(sub2ind(size(M), 1:3, 1:3)) = 1

尝试计算不同列的总和时出错 初步尝试

//This is the column i add into my datagrid
MITTRA.Columns.Add("Min_Tol");
MITTRA.Columns.Add("Max_Tol");
MITTRA.Columns.Add("Min_Weight");
MITTRA.Columns.Add("Max_Weight");

// The following codes is working finely
// if you notice MTTRQT column, it's a data queried from database
for (int i = 0; i <= MITTRA.Rows.Count - 1; i++)
{
    string item = MITTRA.Rows[i]["MTITNO"].ToString();

    Tolerancechecking = database_select4.LoadUser_Tolerance(item);

    MITTRA.Rows[i]["Min_Tol"] = Tolerancechecking.Rows[0]["Min_Tol"].ToString();
    MITTRA.Rows[i]["Max_Tol"] = Tolerancechecking.Rows[0]["Max_Tol"].ToString();

    MITTRA.Rows[i]["Min_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) - ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Min_Tol"]) / 10));
    MITTRA.Rows[i]["Max_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) + ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Max_Tol"]) / 10));

    dataGrid2.Columns.Clear();
    dataGrid2.ItemsSource = null;
    dataGrid2.ItemsSource = Tolerancechecking.DefaultView;

}


//Working Sum computation
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(MTTRQT)", string.Empty));  
MaxTol.Text = Sum.ToString();  /*** This is working as i got my value on the text box ****/

发生错误

  

无效使用了聚合函数Sum()和类型:String。

第二次尝试

  1. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty));

发生错误

  

聚合参数中的语法错误:期望带有可能的'Child'限定词的单列参数。

我将如何使计算和函数起作用?

1 个答案:

答案 0 :(得分:2)

感谢@NoChance提供解决方案。希望这篇文章也能帮助其他人。

/***** This is the part where i declare my datacolumn data type ****/
DataColumn Min_Weight = new DataColumn("Min_Weight");
Min_Weight.DataType = System.Type.GetType("System.Decimal");
MITTRA.Columns.Add(Min_Weight);

/**** This Works finally *****/ 
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty)); 
MaxTol.Text = Sum.ToString();