When retrieving data from a database you must handle null values. The getDefaultIfDBNull method below will check if the value returned from the database is null. If it is null then it will return the default value for that type of object. For example if retrieving an int field from the database and passed a null value and TypeCode of Int32 it will return the default value of 0. This helps streamline the checking for null proccess and ensures that all nulls are handled in a simliar way.
The Code:
/// <summary>
/// Checks if an object coming back from the database is dbnull. If it is this returns the default
/// value for that type of object.
/// </summary>
/// <param name="obj">Object to check for null.</param>
/// <param name="typeCode">Type of object, used to determine what the default value is.</param>
/// <returns>Either the object passed in or the default value.</returns>
public static object getDefaultIfDBNull(object obj, TypeCode typeCode)
{
//If object is dbnull then return the default for that type.
//Otherwise just return the orginal value.
if (obj == DBNull.Value)
{
switch (typeCode)
{
case TypeCode.Int32:
obj = 0;
break;
case TypeCode.Double:
obj = 0;
break;
case TypeCode.String:
obj = "";
break;
case TypeCode.Boolean:
obj = false;
break;
case TypeCode.DateTime:
obj = new DateTime();
break;
default:
break;
}
}
return obj;
}
This is a sample of a method that calls a stored procedure and needs to check for null.
private void FillDetailInfo(int intDetailsId)
{
string conString = "";
SqlDataReader dr;
try
{
conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand("uspGetDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 100000;
cmd.Parameters.AddWithValue("@intDetailsId", intDetailsId);
con.Open();
dr = cmd.ExecuteReader();
//Get details
if (dr.Read())
{
_id = (int)dr["Id"];
_desc = (string)SecurityTools.getDefaultIfDBNull(dr["desc"], TypeCode.String);
_isActive = (bool)SecurityTools.getDefaultIfDBNull(dr["ACTIVE"], TypeCode.Boolean);
}
con.Close();
}
catch (Exception ex)
{
throw ex;
}
}
End Code