1

i am running a query in vb.net and i want to test if the column is null. i have tried:

If reader.GetString(2) IsNot Nothing Then

If IsDBNull(reader.GetString(2)) Then

If reader.GetString(2) IsNot NULL Then

If NOT reader.GetString(2) IS Nothing Then

If NOT reader.GetString(2) IS NULL Then

but they all return:

Data is Null. This method or property cannot be called on Null values.

when i run my query in MySQL, the columns show NULL

0

2 Answers 2

6

The problem is the GetString method that internally cast your row value to a string. If the row value is null you get the exception.

The fix is using the VB.NET ternary operator

Dim result = IF(reader.IsDbNull(2), "", reader.GetString(2))

or if you don't want to assign a default value when the third field is null you could simply write

if Not reader.IsDbNull(2) Then
   .......
End if
Sign up to request clarification or add additional context in comments.

5 Comments

can i use IsNotNull instead?
Sorry but IsNotNull? I am not familiar with this. Where do you have found it?
i didnt, thats why i was asking. or should i do If Not reader.IsDBNull(2) Then
but i want to check if its NOT null and not if it IS null
reader.IsDBNull returns true if the field contains DBNull.Value. The Not operator negate the result so If Not reader.IsDbNull(2) Then enters the if only when the third field of the reader is not null.
0

Just for future reference:

You have a couple of ways to check if the db value is or is not null.
The examples are here with full namespace.

Dim reader As System.Data.SqlClient.SqlDataReader
Dim fieldIndex As Integer = 0

' reader(fieldIndex) is equivalent to reader.Item(fieldIndex)
Dim fieldValue As Object = reader.Item(fieldIndex)

Dim isFieldValueNull As Boolean

' Namespace: System.Data.SqlClient; Class: SqlDataReader
isFieldValueNull = reader.IsDBNull(fieldIndex)

' Namespace: Microsoft.VisualBasic; Module: Information
isFieldValueNull = Microsoft.VisualBasic.IsDBNull(fieldValue)

' Namespace: System; Class: Convert
isFieldValueNull = System.Convert.IsDBNull(fieldValue)

' Namespace: System; Class: DBNull
isFieldValueNull = System.DBNull.Value.Equals(fieldValue)

Note: DBNull.Value always has an instance of DBNull therefore it is never Nothing!

If you would like to check if the database value is not null then you can put the Not keyword before the method call.

Dim isFieldValueNotNull As Boolean

isFieldValueNotNull = Not reader.IsDBNull(fieldIndex)
isFieldValueNotNull = Not Microsoft.VisualBasic.IsDBNull(fieldValue)
isFieldValueNotNull = Not System.Convert.IsDBNull(fieldValue)
isFieldValueNotNull = Not System.DBNull.Value.Equals(fieldValue)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.