Reputation: 135
I have the following code where I convert an int to a string in a list but visual studio does not accept when I try to convert the int into string
Cannot implicitly convert type 'string' to 'int'
listOfUsers.Add(new User
{
Id = myReader["Id"].ToString(),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
What am I missing?
Upvotes: 0
Views: 273
Reputation: 567
Try this code.
listOfUsers.Add(new User
{
Id =int.Parse(myReader["Id"].ToString()),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
Upvotes: 1
Reputation:
You code should be , assuming Id is int.
listOfUsers.Add(new User
{
Id =Convert.ToInt32(myReader["Id"]),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
Upvotes: 2
Reputation: 133403
ID
must of Int
type so you need to covert data to appropriate type.
Here you need to convert value to int type. You can use Convert.ToInt32
Converts the specified string representation of a number to an equivalent 32-bit signed integer.
Example:
Id = Convert.ToInt32(myReader["Id"])
Note: Do remember to check myReader["Id"]
is not DbValue.null
Upvotes: 2