Monday, 24 October 2016

Fix Error - Additional information: Invalid usage of aggregate function Sum() and Type: String.

Watch this example on YouTube
Error - Additional information: Invalid usage of aggregate function Sum() and Type: String.


To fix replace:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ds As DataSet = LoadData()
        Dim query = From rec In ds.Tables(0).AsEnumerable() Select rec
        If ds.Tables(0).Rows.Count > 0 Then
            For Each r As DataRow In query
                Dim s As Integer = IIf(r.Table.Compute("Sum(Age)", "Valid = '1'") Is DBNull.Value, 0, r.Table.Compute("Sum(Age)", "Valid = '1'"))
                MessageBox.Show(s.ToString)
            Next
        End If
    End Sub

    Public Function LoadData() As DataSet
        Dim ds As New DataSet
        Dim dt As New DataTable
        dt.Columns.Add("Valid")
        dt.Columns.Add("Age")
        dt.Rows.Add(New Object() {"1", 33})
        dt.Rows.Add(New Object() {"2", 44})
        dt.Rows.Add(New Object() {"1", 22})
        dt.Rows.Add(New Object() {"1", 22})
        ds.Tables.Add(dt)
        Return ds
    End Function

With 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ds As DataSet = LoadData()
        Dim query = From rec In ds.Tables(0).AsEnumerable() Select rec
        If ds.Tables(0).Rows.Count > 0 Then
            For Each r As DataRow In query
                Dim s As Integer = IIf(r.Table.Compute("Sum(Age)", "Valid = '1'") Is DBNull.Value, 0, r.Table.Compute("Sum(Age)", "Valid = '1'"))
                MessageBox.Show(s.ToString)
            Next
        End If
    End Sub

    Public Function LoadData() As DataSet
        Dim ds As New DataSet
        Dim dt As New DataTable
        dt.Columns.Add("Valid")
        dt.Columns.Add("Age", Type.GetType("System.Int32"))
        dt.Rows.Add(New Object() {"1", 33})
        dt.Rows.Add(New Object() {"2", 44})
        dt.Rows.Add(New Object() {"1", 22})
        dt.Rows.Add(New Object() {"1", 22})
        ds.Tables.Add(dt)
        Return ds
    End Function

No comments:

Post a Comment