IsDBNull check -- translation from VB.Net to C#

E

Earl

In VB.Net, I often check for a null in a dataview column before assigning a
value from that column to a variable:

If Not IsDBNull(dvContacts.Item(0).Item("LastName")) Then
strLastName = CStr(dvContacts.Item(0).Item("LastName"))
Else
strLastName = ""
End If

But I have not figured out how to make the same IsDbNull check in C#.
 
S

sharmilar

Hi,

You can use the code below

if (! (System.Convert.IsDBNull(dvContacts.Item ["LastName"])))
{
strLastName = System.Convert.ToString(dvContacts.Item ["LastName"]);
}
else
{
strLastName = "" ;
}

Thanks
Sharmila
 
P

Peter Johnson

Alternatively to the above comment from Sharmila.

You could create a strongly typed dataset, then any fields which are
nullable will have methods automatically created for them by the
xsd.exe.

So if you had a column called LastName, the following would be how you
would check for nulls.

if (datasetName.table1[0].IsLastNameNull())
{
LastName = string.Empty;
}
else
{
LastName = datasetName.table1[0].LastName;
}

The good thing about creating strongly typed datasets is that it does a
lot of the code for you. And also it's not using the legacy Convert
methods which were only included to allow VB6 developers to quickly
move accross to the .net platform.

Also Typed datasets provide intellisense support so you never mistype
your fieldnames, and they can also be used by either VB.net or C#.

It's taken me a long time to get used to them but well worth my time
spent investigating them.

Here is a good article on strongly typed datasets near the bottom there
is a section which also explains about the IsNull functionality.

http://msdn.microsoft.com/msdnmag/issues/04/12/DataPoints/

Regards,

Pete
 
E

Earl

Thanks to both you and Peter. This is the syntax I will use. I've never been
happy using the strongly typed dataset functionality, altho I'm sure it has
its place.
 
F

Francois Bonin [C# MVP]

A really simple way would be:

if (!dvContacts[0].Row.IsNull("LastName"))
{
// ......
}
else
{
//.....
}
 

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