?
Solved

System.InvalidCastException: Specified cast is not valid.

Posted on 2006-05-22
9
Medium Priority
?
917 Views
Last Modified: 2008-01-09
I using ObjectDataSource and I'm getting a "System.InvalidCastException: Specified cast is not valid." error on the following code.

private const string SP_GET_ALL_USERS = "SELECT * FROM [Mytable]";
SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlCommand myCommand = new SqlCommand(SP_GET_ALL_USERS, myConnection);

        myConnection.Open();
        SqlDataReader reader = myCommand.ExecuteReader();

        while (reader.Read())
        {
           UserA user = new UserA((int)reader["UserID"], (string)reader["FirstName"], (string)reader["LastName          
            userList.Add(user);
       }
 
The error highlights "UserA user = new UserA((int)reader["UserID"], (string)reader["FirstName"], (string)reader["LastName"]);"  What am I doing wrong.
0
Comment
Question by:NBilly
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 13

Expert Comment

by:devsolns
ID: 16738941
The error is what it is.  Have you verified the data coming back?  Are you checking for DBNulls if they exist?  Also the data reader provides Get[Type] methods for data access.  string s = reader.GetString(0);  Without seeing the data I cannot tell you exactly whats wrong.  My guess is your not handling nulls right because a (string) cast will break with nulls.
0
 
LVL 13

Assisted Solution

by:dungla
dungla earned 150 total points
ID: 16739297
You should check the return value from reader before cast to another data type, or simply, put it all in try...catch block like this:
while (reader.Read())
        {
int userID = 0;
try{
userID = (int)reader["UserID"];
}catch{}
           UserA user = new UserA(userID, reader["FirstName"].ToString(), reader["LastName"].ToString());
            userList.Add(user);
       }
0
 
LVL 13

Assisted Solution

by:devsolns
devsolns earned 675 total points
ID: 16739611
No, absolutly dont put it in a try/catch block like that.  With all due respect that is an inappropriate use of exception handling.  Why would you not prevent an error instead of catching?  Exceptions are expensive and in your code you'll swallow exceptions that may have nothing to do with casting.  Also empty catch {} should only be used for non CLS compliant exceptions otherwise your probably not using correctly.

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Accepted Solution

by:
garima_sikarwar earned 675 total points
ID: 16740521
Check for DB Nulls

use :
 UserA user = new UserA((int)reader["UserID"], reader["FirstName"].Tostring(), reader["LastName"].Tostring());  
0
 

Author Comment

by:NBilly
ID: 16744402
If the UserID is a Guid is some coding correct?
0
 
LVL 13

Expert Comment

by:devsolns
ID: 16746707
If UserID is a guid that is why its breaking.  (Guid)reader["UserID"]
0
 
LVL 4

Expert Comment

by:garima_sikarwar
ID: 16749614
If the UserID is GUID, you can not type cast it to int
(int)reader["UserID"] is wrong....

simplest way is to take it in integer... if u wanna type cast
use :
(Guid) reader["UserID"].ToString()
0
 

Author Comment

by:NBilly
ID: 16756294
How can I test for null values and convert it to string at the following level.   I have the field ReceivedDate set to allow null value at the database level because this usually updated sometime later after the record is added.
private string _name

public string RecievedDate
{
  get { return _RecievedDate}
  set {_Received = value};
}
0
 

Author Comment

by:NBilly
ID: 16763996
I corrected the problem by using convert.tostring(reader["myfield"]).  thank you for you suggestions.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month15 days, 21 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question