Wednesday, May 26, 2010

"Specified cast is not valid" when converting to variable from SqlDataReader

Problem:
"Specified cast is not valid." exception thrown from converting data from a SqlDataReader, i.e. short shortVar = (short)reader["shortField"];


Solution:
If your types are actually the same, then this error implies that you must use a Convert.To method.


Example:
buggy: 
short shortVar = (short)reader["shortField"];
fixed:
short shortVar = Convert.ToInt16(reader["shortField"]);

No comments:

Post a Comment

There was an error in this gadget