Member Avatar

I'm trying to load sum of columns to text boxes. but it give me this error:
"Object cannot be cast from DBNULL to other types"
this is code :

query = "SELECT sum(fuel) as ttlfuel, sum(stationery) as ttlstationery, sum(salary) as ttlsalary, sum(vehicle_part) as ttlvp, sum(other) as ttlother FROM mcs.expenses WHERE datee BETWEEN '" & dtpisf.Value & "' AND '" & dtpist.Value & "'"
        Dim cmd = New MySqlCommand(query, con)
        Dim dr As MySqlDataReader
            dr = cmd.ExecuteReader()
            While dr.Read()
                Me.txtfuel.Text = Convert.ToDecimal(dr("ttlfuel"))
                Me.txtstationary.Text = Convert.ToDecimal(dr("ttlstationery"))
                Me.txtcollectorsalery.Text = Convert.ToDecimal(dr("ttlsalary"))
                Me.txtvehiclepart.Text = Convert.ToDecimal(dr("ttlvp"))
                Me.txtotherexpenses.Text = Convert.ToDecimal(dr("ttlother"))
            End While

        Catch ex As Exception
                If (con.State = ConnectionState.Open) Then
                End If
            Catch ex2 As Exception
            End Try
        End Try

Recommended Answers

All 6 Replies

If one of your database columns does not have value then it will return NULL. You can either test for that before you try to convert or you can use a function in your query to return a default value (like zero). The MS SQL function is COALESCE as I recall. I'm about to go out but I can check this with an example when I return.

Member Avatar

there is data in database sir :)

Member Avatar

sir, please read query and tell me is query right or not

One thing to look at, is date supposed to have an extra e on the like you have?

I assumed that datee was a column in his table and was spelled that way because Date is a reserved word. I sill think the problem is because one or more colums is NULL. Should be easy to tell by setting a breakpoint at the first line within the while loop and examining the values in the datareader.

Member Avatar

"datee" was column name .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.