How do i convert an int retrieved from a database to string

  • A+
Category:Languages

I have a login form that I wanna select the userID (which is in the form of an int) from the database, and store it as a string.

string insertQuery =    "SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";  SqlCommand com = new SqlCommand(insertQuery, conn);  com.Parameters.AddWithValue("@Email", tbEmail.Text); com.Parameters.AddWithValue("@Password", tbPassword.Text);  string result = (string)com.ExecuteScalar(); 

But after I login, I get this error:

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

 


What if the record doesn't exist (i.e. the cursor is empty)? Let's read and check if we have at least one record:

// Keep Sql being readable string insertQuery =    @"SELECT UserID        FROM Customers       WHERE Email = @Email         AND Password = @Password";  // Do not forget to dispose IDisposable using (SqlCommand com = new SqlCommand(insertQuery, conn)) {   com.Parameters.AddWithValue("@Email", tbEmail.Text);   com.Parameters.AddWithValue("@Password", tbPassword.Text);    using (var reader = com.ExecuteReader()) {     string result = reader.Read()       ? Convert.ToString(reader[0]) // record exists       : null;                       // cursor is empty      //TODO: put relevant code which works with result here   } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: