Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > ASP .Net > Casting a DBNull

Thread Tools

Casting a DBNull

.Net Sports
Posts: n/a
I'm trying to match fields from XML feed to a datarow, but I get a
"System.InvalidCastException: Object cannot be cast from DBNull to
other types" error at the PkgAmount line. This code was converted from
original C# code, so I'm wondering if it has something to do with C#'s
strict datatype criteria (even tho this is in, or I need to do
something extra around the
FormatAmount(Convert.ToSingle(drwData("PkgAmount") )) ...
Dim drwData As DataRow
For Each drwData In dtaData.Rows
Dim SID As String = "SID=" & Convert.ToString(drwData("ID")) & "&"
Dim PurchaseTypeID As String = Convert.ToString(drwData("PurchaseID"))
Dim PkgAmount As String =
FormatAmount(Convert.ToSingle(drwData("PkgAmount") ))

Reply With Quote
Cor Ligthert [MVP]
Posts: n/a

Why not write it in VB.Net code (However, you can in C# as well not use a
string as a single)

Altough it is a little bit strange code, alone the last line will fill the
items which are inside the method so those can never be used.

Dim drwData As DataRow
For Each drwData In dtaData.Rows
Dim SID As String = SID=" & drwData("ID").ToString & "&"
Dim PurchaseTypeID As String = drwData("PurchaseID").ToString
Dim PkgAmount As Single = Csng(drwData("PkgAmount"))
''Or just as the other strings,

I hope this helps,


Reply With Quote
David Hubbard
Posts: n/a
I am not sure if this helps but in C# if you have a nullable value say a
birthday that can be read from db then you would use

DateTime? fBirthday;

// read from db

// save as string

String tmp = ""

if ( fBirthday != null )
tmp = ( (DateTime) fBirthday ).Date;

Sorry but I don't know vb, but I have to do similiar things for columns that
can be null in some tables.
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Up casting and down casting Sosuke C++ 2 12-20-2009 03:24 PM
Problem with depracated casting method (down casting) Wally Barnes C++ 3 11-20-2008 05:33 AM
Another question about inheritance (up-casting and down-casting) kevin Java 11 01-08-2005 07:11 PM
Adding a DBNull value to the database Boris Zakharin ASP .Net 0 08-27-2003 12:53 AM
Question: Best way to handle DBNULL in datareaders Ravikanth[MVP] ASP .Net 6 07-18-2003 10:51 AM