Search code examples
c#asp.netsqlsql-servertype-conversion

SQL, C# - Can't convert int32 to string?


Alright, so I have the following SQL query:

 query.CommandText = "SELECT FirstName, LastName, Age FROM Characters WHERE LastName LIKE   '"+name+"' ORDER BY Age";

And this loop that stores the result in the string "output"

while (reader.Read()) {
    output = output + reader.GetString(0) + reader.GetString(1) + reader.GetString(2).ToString();
}

However, for the third attribute age, which is an int, I get an error

could not convert System.Int32 to type System.String

As you see, I've already tried to solve this by using the int.ToString() function but I still get the same error. What am I doing wrong here? Thanks in advance!


Solution

  • agree with Tim but something like

    reader[2].ToString();
    

    may be more generic and less buggy if you change your select order.

    following Tim Comment:

    reader["Age"].ToString();