1

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

4
  • Like this: string insertQuery = "SELECT CONVERT(NVARCHAR(20),UserID) FROM Customers WHERE Email = @Email AND Password = @Password"; Commented Dec 28, 2018 at 12:48
  • 1
    Instead of (string) in front if it, add .ToString() behind it. Commented Dec 28, 2018 at 12:52
  • 1
    Why do you want to do that? What's wrong with keeping it an int? Commented Dec 28, 2018 at 12:52
  • 1
    If the value is an integer then use an int to read it. This seems like an X-Y Problem. Commented Dec 28, 2018 at 12:58

6 Answers 6

7

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can try using like below

string result = Convert.ToString(com.ExecuteScalar());

Comments

1

ExecuteScalar returns Object type and you can convert it into which ever type you like

public override object ExecuteScalar ();

You can call it's ToString() method and it returns string form of it's value.

Comments

1

Try this,

string result = string.Empty;

SqlCommand com = new SqlCommand(..);
..
object executedResult = com.ExecuteScalar();

if(executedResult != null) {
   result = executedResult.ToString();
}

Hope helps,

Comments

1

Probably the simplest solution would be (assuming query always return result):

string result = com.ExecuteScalar().ToString();

You can cast as nvarchar in your query also:

string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";

Comments

0

Below are my findings

    string userID;

using(SqlConnection conn = new SqlConnection(connectionString))
{
            string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND 
            Password = @Password";
            SqlCommand com = new SqlCommand(insertQuery, conn);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
            com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
            SqlDataReader reader = com.ExecuteReader();
            while(reader.Read())
            {
              userID = reader["UserID"].ToString();
            }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.