I use the following line to convert the datarow
value into double.
double.parse(Convert.ToString(datarow));
If the datarow
is DBNULL
, I am getting the following exception:
'double.Parse(Convert.ToString(data))' threw an exception of type 'System.FormatException'
How to handle this one without using tryparse.
DBNull
can't be cast or parsed todouble
(orint
,decimal
, etc), so you have to check ifdatarow
isDBNull
before trying to parse it. It should be a oneliner using the ternary operator:I have a bunch of conversion utility methods for such scenarios, in the format similar to this.
I use this kind of weak-to-strong type conversion utilities mostly when I work with ADO.NET stuff, or other weakly typed interfaces, like reading data from Excel for example.
In my real code I also allow to pass a
CultureInfo
for string conversion, and do some other stuff like normalizing decimal signs, etc. to achieve the best format tolerance.The general catch clause could be improved of course by catching specific exception types like
FormatException
, but for my needs it works good.Another alternative would be to check if the
datarow
isDBNull
:This way, you do not need to check for
DBNull.Value