I'm querying a SQL DB and sometimes the result is Null, so I thought I would test this but my code results in an error "Data is Null. This method or property cannot be called on Null values."

Here is a snipet of my code:

For i = 5 To 6
cmd = New MySqlCommand(query2t & i, db)
rdr = cmd.ExecuteReader()
rdr.Read()
If Not IsDBNull(rdr.GetUInt32(0)) Then
AfterHour.Series(1).Points.AddXY(Daysofweek(i), FormatNumber(rdr.GetUInt32(0)))
Else
AfterHour.Series(1).Points.AddXY(Daysofweek(i), 0)
End If
rdr.Close()
Next

Can anyone help me with that?

Thanks a lot.

The error comes on the "If Not IsDBNull(rdr.GetUInt32(0)) Then" line.

The error is: SqlNullValueException was unhandled"
Then: "Data is Null. This method or property cannot be called on Null values."

Where do I put that?

Sorry to ask but I'm just a beginner and I don't know that IIF function.

ur line If Not IsDBNull(rdr.GetUInt32(0)) Then

remove that with IIf(IsDBNull(rdr.GetUInt32(0))), 0, rdr.GetUInt32(0)))) Then

I changed my code to:

For i = 5 To 6
cmd = New MySqlCommand(query2t & i, db)
rdr = cmd.ExecuteReader()
rdr.Read() 'Read Database
tmp = IIf(IsDBNull(rdr.GetUInt32(0)), 0, FormatNumber(rdr.GetUInt32(0)))
AfterHour.Series(1).Points.AddXY(Daysofweek(i), tmp)
rdr.Close()
Next


And I get the same error on the "Tmp = ..." line.

Which database are u using? what is rdr? are u not getting any syntax error?
IIF should work. Else try to handle the situation in SQL query itself.using ISNULL function in ur select statement.

Try it like this:

tmp = IIf(IsDBNull(rdr(0)), 0, FormatNumber(rdr(0)))

It appears that you cannot use .GetInt32 in an IsDBNull function. Additionally because IIf statements run both sides of the true/false statement if you want to use rdr.GetInt32(0) when it is true you will have to use a standard if statement. This at least seems to be the case in a quick test i just performed.

Hope this helps!

Thank you so much for the advice, Atove.

I ended up using a regular If Statement with rdr(0):

For i = 5 To 6
cmd = New MySqlCommand(query2t & i, db)
rdr = cmd.ExecuteReader()
rdr.Read() 'Read Database
If IsDBNull(rdr(0)) Then
AfterHour.Series(1).Points.AddXY(Daysofweek(i), 0)
Else
AfterHour.Series(1).Points.AddXY(Daysofweek(i), FormatNumber(rdr.GetUInt32(0)))
End If
rdr.Close()
Next

This question has already been answered. Start a new discussion instead.