Skip to content Skip to sidebar Skip to footer

Handle Null In Datareader

This is the code I' using for reading data from sql through DataReader. It gives Error when there is a NULL in table. How to handle it? I tried c.ActualWeight= dr[0] as float? ??

Solution 1:

You can use SqlDataReader.IsDBNull to check for null values out of a data reader. C# null and DBNull are different.

 c.ActualWeight = 
     dr.IsDBNull(0) 
     ? default(float) 
     : float.Parse(dr[0].ToString().Trim());

Solution 2:

You can try this

if (dr.IsDBNull(0))
   c.ActualWeight = default(float);
else
   c.ActualWeight = float.Parse(dr[0].ToString().Trim());

Solution 3:

c.ActualWeight = (dr[0] != DBNull.Value) ? float.Parse(dr[0].ToString().Trim()) 
                                         : default(float)

use the DBNull.Value to check for null values.

Post a Comment for "Handle Null In Datareader"