adding items to a listbox that are null problem

M

mrmagoo

I'm trying to add an object to a listbox. I'm using a DataReader from a
resultset from a stored procedure.

It works except when there are NULL in any of the rows. Then I get an error:

An unhandled exception of type 'System.InvalidCastException' occurred in
microsoft.visualbasic.dll
Additional information: Cast from type 'DBNull' to type 'String' is not
valid.

Me.lstMenu.Items.Add(New Menu(dr.Item("FirstTier"), dr.Item("SecondTier")))

How do I handle nulls? FirstTier is a string, SecondTier is a Long.

If I remove all nulls in the table, this works, but I need to keep the
nulls, so I need a solution..

Thanks. Any help is appreciated.
 
P

Peter Proost

Hi, you can handle them in you select statement or you can build in a check
in .net something like

if not dr.Item("FirstTier") Is DBNull.Value then ...

Hth

Greetz, Peter
 
M

mrmagoo

thanks...how would I optimally do that with the Add approach I
posted...adding an object to the listbox.

thanks
 
P

Peter Proost

You could build the check in the constructor of your Menu class, it's just
what you prefer

Greetz,

Peter
 
M

mrmagoo

Ok...but how do I do it?

Sub New(ByVal FirstTier As String, _
ByVal SecondTier As Long)

If there's a null, it errors out even before the constructor begins. There's
a NULL being passed as a parameter value to the constructor, which is
expecting a string. There's where the error is occurring.

How do I implement your suggestion?

thanks
 
M

mrmagoo

Thanks for the help everybody.

I'm gonna try these different approaches out.

Much appreciated!
 
R

Renze de Waal

You could create a function that takes a parameter with type object and
returns a string. Something like

private function ReplaceNull(byval objValue as Object) as string
If objValue is DBNull.Value Then
ReplaceNull = ""
Else
ReplaceNull = CType(objValue,String)
End If
end function

Then change your call to

Me.lstMenu.Items.Add(New Menu(ReplaceNull(dr.Item("FirstTier")),
ReplaceNull(dr.Item("SecondTier"))))

Best regards,

Renze de Waal.
 

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