簡體   English   中英

如何在C#中查找數據表中的列總和

[英]How to find sum of columns in datatable in c#

我正在使用以下代碼,但沒有得到任何結果,而是一片空白,並拋出諸如

Object cannot be cast from DBNull to other types.

第三和第四列是FFBW

數據表的值會像

C1   c2    FF  BW

56  122    3   4

23  45         7

45  78     6   

12  34     6   9

我想將總FF設為15,將總BW設為20

   decimal FF = 0,  BW = 0, AF = 0;

 DataTable table = dtPointLinks.Clone();
                table.Columns[0].DataType = typeof(string);
                table.Columns[1].DataType = typeof(string);
                table.Columns[2].DataType = typeof(string);
                table.Columns[3].DataType = typeof(string);


                // Declare an object variable.
                object objFF;
                objFF = table.Compute("Sum(FF)", string.Empty);
                object objBW;
                objBW = table.Compute("Sum(BW)", string.Empty);
                FF = Convert.ToDecimal(objFF);
                BW = Convert.ToDecimal(objBW); 

不知道這里出了什么問題

在您的情況下,您可以嘗試傳統上的for循環以獲得所需的答案。

下面的示例代碼顯示了如何實現此目的。

        decimal FF = 0;
        decimal BW = 0;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if(dt.Rows[i]["FF"].ToString() != "")
            {
                FF += Convert.ToDecimal(dt.Rows[i]["FF"].ToString());
            }
            if (dt.Rows[i]["BW"].ToString() != "")
            {
                BW += Convert.ToDecimal(dt.Rows[i]["BW"].ToString());
            }     
        }

最終結果將是FF = 15BW = 20

希望這可以幫到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM