简体   繁体   中英

vb.net - read null value from database

I have a database where in column there is no value (so it's null ), but I can't handle this in vb.net. I tried with this code:

            reader.Read()
            If String.IsNullOrEmpty(reader.GetString(0)) Then
                Return
            Else
                tilbulfolderTextBox.Text = reader.GetString(0)
            End If

and also with:

If reader.Read() = False Then

and with:

If IsDBNull(reader.Read()) Then

But apparently it doesn't work because I get exception on the statement after the Else that I can't get Null values with this method. I guess you will figure out what I require from the program by reading the code itself.

The IsDBNull method of the DbDataReader base object is defined to handle this situation.
Of course you can't try to read something if the reader.Read() returns with false (meaning no more rows are available)

    If reader.Read() Then
        If reader.IsDBNull(0) Then
            Return
        Else
            tilbulfolderTextBox.Text = reader.GetString(0)
        End If
   End If

Also, I don't see more of your code, but keep in mind that returning in this way could be very wrong if you don't close the connection and dispose the objects involved in this operation

And, yes, as others have pointed out, there is also a function called IsDBNull from the Microsoft.VisualBasic assembly, but, I prefer to use the methods provided by the classes defined in the .NET framework and not the ones provided for compatibility with previous versions of VB

You should use IsDbNull function to comapre it with null :

        reader.Read()
        If IsDbNull(reader(0)) OrElse String.IsNullOrEmpty(reader.GetString(0)) Then
            Return
        Else
            tilbulfolderTextBox.Text = reader.GetString(0)
        End If

.Net has a different type for handling SQL NULLs: DbNull .

Check this post about how to handle it: handling dbnull data in vb.net

In your case, you need the IsDbNull function, check this MSDN Documentation about it.

If IsDbNull(data) Then
    return
Else
    tilbulfolderTextBox.Text = data
End If

use IsDBNull function to ensure that the value from DataReader is null or not. Then proceed the code flow.

Sounds like your IF may not be working properly

Try using IsDBNull instead.

IsDBNull is a boolean variable and can be used like the following;

reader.Read()

If Not IsDbNull(reader.GetString(0)) Then
    tilbulfolderTextBox.Text = reader.GetString(0)
Else
    return
End If

try this

reader.Read()
        If IsDbNull(reader.GetString(0)) Then
            Return
        Else
            tilbulfolderTextBox.Text = reader.GetString(0)
        End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM