数据表 vb.net 2010 中的 sum 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25101897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:03:02  来源:igfitidea点击:

sum column in datatable vb.net 2010

vb.netdatatablesum

提问by Peps

I am trying to get the sum of the column TotalAmountin my DataTabledtbut I always get this error:

我试图让列的总和TotalAmountDataTabledt,但我总是得到这样的错误:

Object reference not set to an instance of an object.

你调用的对象是空的。

I am using VB in Visual Studio 2012.

我在 Visual Studio 2012 中使用 VB。

Here's the code:

这是代码:

Dim table As DataTable = CartDataSet.Tables("dt")
Dim result As Integer
result = table.Compute("SUM(TotalAmount)", "")

Screenshot

截屏

回答by Mitch Wheat

You are trying to de-reference a NULL object reference, which means tableis NULL.

您正在尝试取消引用 NULL 对象引用,这意味着tableis NULL

That in turn, means CartDataSetdoes not contain a table named "dt"

反过来,意味着CartDataSet不包含名为的表"dt"

回答by Amit Patel

Dim result As Object
result = table.Compute("SUM(TotalAmount)", "") 

then do result.ToString() you will get your output

然后做 result.ToString() 你会得到你的输出

回答by Quethzel Díaz

You can use linq, like this.

您可以像这样使用 linq。

Dim result As Decimal = dt.AsEnumerable().Sum(Function(row) row.Field(Of Decimal)("TotalAmount"))

回答by Abdul

Possible Issues

可能的问题

  • Table is null
  • No records in the table
  • 表为空
  • 表中没有记录

Solutions:

解决方案:

1- Better to check the datatable status before computation like

1-最好在计算之前检查数据表状态,例如

If Not table Is Nothing AndAlso table.Rows.Count > 0 Then
...
End If

2- Check for DBNULL while computing in case no records

2- 在计算时检查 DBNULL 以防没有记录

IIf(IsDBNull(table.Compute("SUM(TotalAmount)", "")), "0", table.Compute("SUM(TotalAmount)", ""))

回答by Yocto Karthi

Dim dt As DataTable = TajDataSet.Tables("MAtab")
Dim sum As Integer = Convert.ToInt32(dt.Compute("SUM(ServiceCharge)", String.Empty))
SCC.Text = sum.ToString

回答by DCraft

For the ".Compute" function to work, you have to declare your variable "result" as "object" instead of "integer". Then later you can convert the value in "result" to an integer using "Convert.ToInt".

要使“.Compute”函数工作,您必须将变量“result”声明为“object”而不是“integer”。然后,您可以使用“Convert.ToInt”将“result”中的值转换为整数。

Dim result as object