Home > front end >  CS0029: Unable to cast object of type 'System.Int32' to type 'System.String'
CS0029: Unable to cast object of type 'System.Int32' to type 'System.String'

Time:01-22

  1. Summarize the problem

Adding an object to a list after reading its properties from a SQL Server SELECT statement - I get this error:

System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'

Include details about your goal

  • My goal is to read asset changes from the database by using a SELECT T-SQL statement, reading and appending them into a list and display them using the list in a view.

Describe expected and actual results

  • Expected: No error pops up.

  • Actual: The error mentioned earlier pops up.

Include any error messages

  • Already mentioned earlier.
  1. Describe what you’ve tried

Show what you’ve tried and tell us what you found (on this site or elsewhere) and why it didn’t meet your needs. You can get better answers when you provide research.

//UserID = reader.GetString(0),
//AssetID = reader.GetString(1),
UserID = reader.GetInt32(0).ToString(),
AssetID = reader.GetInt32(1).ToString(),
  • Making sure both variables UserID and AssetID use int

The same error still pops up.

CodePudding user response:

Since both your variables/properties are integers you shouldn't convert them to strings:

UserID = reader.GetInt32(0),
AssetID = reader.GetInt32(1),

If you later need to add them to list of strings the you can call ToString there (UserID.ToString(), AssetID.ToString())

CodePudding user response:

you can't implicitly assign string to integer, you need to parse the string, in this case using int.Parse

your code could me something like this:

UserID = int.Parse( reader.GetInt32(0).ToString());
AssetID = int.Parse(reader.GetInt32(1).ToString());

for more information about follow this link.

  •  Tags:  
  • Related