How to avoid error when displaying empty MS Access fields in VB?
Hi,
I have a database with lots of fields, some of which are still empty and are to be filled in at a later stage. Is there any way of writing an IF statement (or any other method) that will allow these empty records to be 'shown' in my textboxes in Visual Studio, without receiving the error:
Conversion from type 'DBNull' to type 'String' is not valid.
?
Thanks in advance.
Collin
collin_ola
Junior Poster in Training
54 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
You could possibly make a function that converts DBNull to an empty string like:
Function SafeValue(ByVal objOrig As Object) As String
If (IsDBNull(objOrig)) Then
Return ""
End If
Return objOrig.ToString()
End Function
... then wrap all of your potential DBNull returned strings in that.
thines01
Postaholic
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
SQL server supports the COALESCE function. I seem to recall that Access has something similar
Nz(Value, [ValueIfNull])
I don't have Access installed so I can't verify this.
Reverend Jim
Posting Shark
1,167 posts since Aug 2010
Reputation Points: 253
Solved Threads: 159
Hey guys,
Sorry for the very late reply.
I'm sure that the COALESCE function would be a way of solving the issue, but I'm not too sure how to use it, and it isn't described to clearly in the link provided by waqasaslammmeo...
collin_ola
Junior Poster in Training
54 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Coalesce takes an arbitrary number of parameters. It returns the value of the first parameter that does not evaluate as NULL. If all parameters are NULL then it returns NULL. For example
COALESCE(a,b,c)
if a is not null then
return a
else if b is not null then
return b
else
return c
end if
I think NZ is similar but takes only two arguments. The second argument is the value you want returned if the first argument is NULL. For example
NZ(middleName,'none')
Retuens the middleName field. If there is no middle name value then it returns "none".
Reverend Jim
Posting Shark
1,167 posts since Aug 2010
Reputation Points: 253
Solved Threads: 159
Oh right..thank you :). I'll try it out tomorrow, it's nearly midnight here :P
collin_ola
Junior Poster in Training
54 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0