How to easily parse DBNull value into other data type

H

Hon Yuen, Ng

Hi

This is a newbie question.
I've a datatable that contains null value. Sometime i need to store this
data into different variables. However, error will be thrown if the data
i tried to stored in the variable is a null value.

E.g.
Dim int As Int64
Dim null As Object
null = DBNull.Value
int = null 'this will throw error

To solve this, i have to check if the value is DBNull each time. Is
there a simpler way to do this?

Thanks in advance.

From,
Hon Yuen, Ng
 
M

Michael C#

I usually create a function like this:

Function SafeString(ByVal o As Object) As String
Dim s As String = String.Empty
If Not (o Is Nothing OrElse o Is DBNull.Value) Then
s = Convert.ToString(o)
End If
Return (s)
End Function

This function returns an empty string if you pass it an DBNull.Value. Also
note that the object is first checked to make sure it is not Nothing. If
you're pulling data from a SQL Server, you can use the COALESCE() function
on the Server-Side to perform a similar function before it ever gets to your
client app.

Thanks,
Mike C
 
M

Michael C#

P.S. - For Numeric values you can use a similar function, but return a 0 for
DBNull.Value or Nothing.

Thanks,
Mike C.
 
H

Hon Yuen, Ng

Thanks for your reply.
I think i understood what you mentioned. However, what if i do data
binding? If i bind a data table to a TextBox, and the data is a
DBNull.Value? What is the best practice to solve this kind of problem?

Thanks in advance.

From,
Hon Yuen, Ng
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top