Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
int resourceType = row.Field<int>("jbd_jobno");

getting an error specified cast is not valid.

"jbd_jobno" is an integer

Please help me out
Posted
Updated 3-Nov-14 18:40pm
v3
Comments
[no name] 4-Nov-14 0:29am    
What is row ? A dataRow ?
syed shanu 4-Nov-14 0:32am    
you need to convert it into integer
int resourceType = Convert.ToInt32(row.Field("jbd_jobno"));

hope this will help you.
Sergey Alexandrovich Kryukov 4-Nov-14 0:52am    
What is the actual column type?
For example, it could be "int?" (nullable), or something else.
—SA

Please check SQL Server Data Type Mappings (ADO.NET)[^] and make sure you have selected correct type in c# for your database column type. If your column support null values you need to use nullable type as below
C#
int? resourceType = row.Field<int?>("jbd_jobno");
 
Share this answer
 
v5
Comments
[no name] 4-Nov-14 0:34am    
Yes. Do it this way. because by default the table will be of object type. You will have to convert it this way
Sergey Alexandrovich Kryukov 4-Nov-14 1:12am    
Let's be logical: if first line (as OP did, with int, not with "int?") throws exception, why would your second line work?
Yes, if required runtime type is int, it can always cast to "int?", but not visa versa, so, required type is not int.
Please see my answer which should clarify it.
—SA
Some clarification to Solution 1 (please see my comment to it):

Please look at the declaration of this extension method:
http://msdn.microsoft.com/en-us/library/bb360891%28v=vs.110%29.aspx[^].

For some data row and some column name, the method attempts to get the attribute value for this row. Even though this syntax itself is strongly typed, there is no such thing as miracle: the runtime type for the attribute may or may not be assignment-compatible with the actual generic parameter type you use (int, in this case). If it is not compatible, type cast is failed, throws exception you show. You need to use correct value type for this call, which is itself correct. Just find out what is the correct type expected.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900