0

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

Pang
  • 8,605
  • 144
  • 77
  • 113
Peps
  • 1
  • 1
  • 2
  • 5

7 Answers7

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

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

Amit Patel
  • 147
  • 1
  • 5
1

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"

Mitch Wheat
  • 280,588
  • 41
  • 444
  • 526
0

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)", ""))
Abdul
  • 2,809
  • 1
  • 10
  • 5
0
Dim dt As DataTable = TajDataSet.Tables("MAtab")
Dim sum As Integer = Convert.ToInt32(dt.Compute("SUM(ServiceCharge)", String.Empty))
SCC.Text = sum.ToString
Vivek S.
  • 15,777
  • 6
  • 54
  • 78
0

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
DCraft
  • 1
0

You can use linq, like this.

Dim result As Decimal = dt.AsEnumerable().Sum(Function(row) row.Field(Of Decimal)("TotalAmount"))
Quethzel Díaz
  • 479
  • 1
  • 9
  • 20
0

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

Dim result As Integer

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