Monday, April 8, 2013

Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception

Many a times when we are getting data from database and showing them on page in asp.net we came across this error "Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception"
The main reason for this error is that when we are getting data from database and we get Null value and we try to cast it into string or any other data type .We can easily resolve this error by just adding small condition before casting into any data type
I have included syntax in vb  as well as c#.Here is the trick what we have to do:
Vb.Net
string s=IIf(IsDBNull(db.rd("column")), String.Empty, db.rd("column"))
C#
string s = ( IsDBNull(db.rd("column")) ? String.Empty : db.rd("column") );

No comments :

Post a Comment