Monday, March 12, 2012

How to handle DBNull

As i write some functions to return string or dataset from database, there is a chance of return DBNULL.

Even i checked the dr(0) with Nothing, It still get Error
dim dr as sqldatareader = xxx.executeQuery
if dr.Read() then
if dr(0) <> Nothing Then
dim abc as string = dr(0)
end if
end if

How can i solve this?
Thx a lotsThere is ISDBNull function in VB and also isDBNull method in SqldataReader, which you can use to check if field is null. If field is null (DBNull), you should set the member/variable you set based on this field, so that its value clearly indicates it has not been set, for example with string it could be String.Empty.
thx for your quick respone

Labels: , , , , , , , , , ,

How to handle boolean values from Access

I use a DataReader to retrieve my database (field)information. Everything works fine when working with strings.

Ex.

string data1 = MyReader["FieldName"].ToString();

But now I want to store a boolean value from the database in a variable, but how? Seems stupid, but I cant get it working. It's an Acces database with a yes/no field in the table. I want something like this:

bool data2 = MyReader["FieldName"];

but then asp.net tells me: cant convert object to bool.

What to do...

Hi,

you need to cast it to boolean

bool data2 = (bool)MyReader["FieldName"];


ok, thanks for your (simple) solution! But I do think this is the ugly way. Isn't there a function like ToString() but then for booleans? Or thould I forget the ugly thing about it and simply use a cast?

You'll see lots of casting when working with .NET so get used to it. :-)

You can useConvert.ToBoolean in .NET (Convert is a helper class in the Framework) if it's the prettier way for you

Labels: , , , , , , , , , , , , ,