A personal repository of technical notes. - CSC

DBNull Handling and Conversions

Invalid Conversions of DBNull.Value

string myStr = (string)dbRecord["DBCOLUMN"]; // Unable to cast object of type 'System.DBNull' to type 'System.String'.
int myInt = Convert.ToInt32(dbRecord["DBCOLUMN"]); // Object cannot be cast from DBNull to other types.
bool myBln = (bool)dbRecord["DBCOLUMN"]; // Specified cast is not valid.
bool myBln = Convert.ToBoolean(dbRecord["DBCOLUMN"]); // Object cannot be cast from DBNull to other types.


Valid Conversions of DBNull.Value

string myStr = dbRecord["DBCOLUMN"] as string; // Converts to null
string myStr = Convert.ToString(dbRecord["DBCOLUMN"]); // Converts to empty string

int myInt = (dbRecord["DBCOLUMN"] == DBNull.Value) ? 0 : (int)dbRecord["DBCOLUMN"]; // Integer to 0 if DBNull
int myInt = (dbRecord["DBCOLUMN"] == DBNull.Value) ? (short)0 : (short)dbRecord["DBCOLUMN"]; // Cast SQL smallint to C# int
bool myBln = (dbRecord["DBCOLUMN"] == DBNull.Value) ? false : (bool)dbRecord["DBCOLUMN"]; // Boolean to false if DBNull
myBln = (dbRecord["DBCOLUMN"] == DBNull.Value) ? false : (dbRecord["DBCOLUMN"].ToString().ToUpper() == "Y"); // String to Boolean with DBNull check
DateTime myDateTime = (dataReader["DBCOLUMN"] == DBNull.Value) ? DateTime.MinValue : Convert.ToDateTime(dataReader["DBCOLUMN"]); // DateTime to DateTime

References
?: Operator (C# Reference)
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Convert Class (System)
http://msdn.microsoft.com/en-us/library/system.convert(VS.80).aspx

as (C#)
http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.80).aspx

No comments:

Post a Comment