creating a property in a Class to avoid DBNull

  • Thread starter Thread starter Bruno Alexandre
  • Start date Start date
B

Bruno Alexandre

Hi guys,

I created a Class to my program, and it runs fine except one little
detail...

when the Database Value is Null I always get an Error when using it

user.name = trim(reader.item("tName"))

How can I avoid this?

I have

public class user
(...)

private strName as string = ""

property name() as string
get
return strName
end get
set(byval value as string)
strName = value
end set
end property

(...)
end class


how can I test the value for System.DBNull ? I always get error messages
saying that I can't use If Value.IsNullorEmpty Then (...)

--



Bruno Alexandre
(Sintra, PORTUGAL)
 
Bruno Alexandre said:
I created a Class to my program, and it runs fine except one little
detail...

when the Database Value is Null I always get an Error when using it

user.name = trim(reader.item("tName"))

\\\
Dim o As Object = Reader.Item("tName")
If IsDBNull(o) Then
User.Name = ""
Else
User.Name = DirectCast(o, String)
End If
///
how can I test the value for System.DBNull ? I always get error messages
saying that I can't use If Value.IsNullorEmpty Then (...)

Either use 'IsDBNull' or 'If x Is DBNull.Value Then...'.
 
I hope that I could do such thing in the class property... guess not.

But what the heck ;) it works fine

Thank you

--



Bruno Alexandre
(Sintra, PORTUGAL)
 
Bruno Alexandre said:
Hi guys,

I created a Class to my program, and it runs fine except one little
detail...

when the Database Value is Null I always get an Error when using it

user.name = trim(reader.item("tName"))

How can I avoid this?

It is possible to passing Nothing as the set value of a string property.
Assume your USER class has the following:

private _Name as string

Public Property Name() as String
Set(ByVal value as string)
_Name = value.trim
End Set
....

if you can find yourself running into an instance where you pass it a null
as in:
user.name=Nothing

This can most frequently be found when populating values from the database
or when clearing the selected value on a combo box set as a dropdownlist. To
remedy this, adjust the Property setter as follows:

Public Property Name() as String
Set(ByVal value as string)
If value is nothing then value = ""
_Name = value.trim
End Set
....

This assumes you do not actually want a Nullable (Of String) type in this
case.

Jim Wooley
www.devauthority.com/blogs/jwooley
 
Back
Top