0
  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.

  1. Show some code

When appropriate, share the minimum amount of code others need to reproduce your problem (also called a minimum, reproducible example)

I don't know how to produce a minimum example without breaking the project in one way or another.

There's the link to download the project. After downloading it, extract and run it.

The email address and password are john@gmail.com and john123 respectively. You should see "Asset History" on the top navigation bar. Click on it to produce the problem.

Weizhong Lee
  • 15
  • 1
  • 9

3 Answers3

0

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())

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I tried it. It didn't work. ToString() doesn't either. I'll try to see which property/properties is/are in `int` before adding them to the SQL table to pinpoint the problem. – Weizhong Lee Jan 22 '22 at 12:18
0

The GetString Method (Int32) needs an integer (column index) as a parameter.Additionally you can add ToString() after transactions.

UserID = reader.GetString(reader.GetOrdinal("Column Name")),
AssetID = reader.GetString(reader.GetOrdinal("Column Name")),
-2

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.

MorenajeRD
  • 849
  • 1
  • 11
  • 27
  • 3
    `GetInt32` already returns `int` so you are basically converting int to string and then back to int, which is pointless – Guru Stron Jan 22 '22 at 06:19