0
votes

I am trying to get the sum of the column TotalAmount in my DataTable dt but I always get this error:

Object reference not set to an instance of an object.

I am using VB in Visual Studio 2012.

Here's the code:

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

Screenshot

7

7 Answers

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

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

1
votes

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

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

0
votes

Possible Issues

  • Table is null
  • No records in the table

Solutions:

1- Better to check the datatable status before computation like

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

2- Check for DBNULL while computing in case no records

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

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".

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

You can use linq, like this.

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

Dim table As DataTable = CartDataSet.Tables("dt")

Dim result As Integer

result = IIf(IsDBNull(dtable.Compute("SUM(TotalAmount)",""),0,dtable.Compute("SUM(TotalAmount)", ""))