Reputation: 7268
Usually "specified cast is not valid" errors are easy to solve. But this one has gotten my head scratching.
I have a SQL compact
database integrated in my C#
application. At the moment I am getting the current database structure and putting it into a datatable. The SQL command im using is:
select * from information_schema.columns
One of the columns is NUMERIC_PRECISION
, which is a numeric value.
I try and store this information in an integer variable, but it tells me the specified cast is not valid. The code is:
int precision;
if (row["NUMERIC_PRECISION"] != DBNull.Value)
precision = (int)row["NUMERIC_PRECISION"];
My question is why is this operation invalid? The cell is a numeric value and I am trying to cast it to an integer - surely in theory this should work?
Upvotes: 0
Views: 2220
Reputation: 17194
The best practice is to: int.Parse(string s)
precision= Convert.ToInt32(row["NUMERIC_PRECISION"]);
Upvotes: 0
Reputation: 109577
[EDIT] Now you said it's a string: You must parse it.
Try: precision = int.Parse((string)row["NUMERIC_PRECISION"]);
That will throw an exception if it isn't in the correct format, so you must either be prepared to catch the exception, or use an overload of int.TryParse() to check its validity.
[EDIT2]
It seems that the data is not a string; it is an Int16. So do this:
precision = (Int16)row["NUMERIC_PRECISION"];
Upvotes: 0
Reputation: 2683
since you said that the value could be null, I would actually use a nullable integer to store it in.
int? precision = null;
if(row["NUMERIC_PRECISION"] != DBNull.Value) //or whatever you want to do to make sure it actually has a value
{
//I usually use Convert.ToInt32 since its easier, but it is also more sensative
precision = Convert.ToInt32(row["NUMERIC_PRECISION"]);
}
the Convert
class is easy to use and visibly makes a lot of sense, its very sensitive to null or improperly formatted values though, and throws an exception when it finds one.
Upvotes: 2
Reputation: 17080
Try using int.parse instead of simple casting to int - http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx
Upvotes: 0
Reputation: 12654
row["NUMERIC_PRECISION"] returns object that has an numberic typed boxed in it. You can cast it only to the exact type of this boxed object.
try casting to (decimal) or (long) first , and then to (int).
You can check the type of row["NUMERIC_PRECISION"] using debugger watch.
You can also ask Convert class to handle conversion for you:
precision = Convert.ToInt32(row["NUMERIC_PRECISION"]);
Upvotes: 1