Hashim Alshareef
Hashim Alshareef

Reputation: 47

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

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

Upvotes: 1

Views: 1378

Answers (6)

Sravan Kumar
Sravan Kumar

Reputation: 1

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

Upvotes: 0

Pawel Czapski
Pawel Czapski

Reputation: 1864

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";

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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
  }
}

Upvotes: 7

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

Try this,

string result = string.Empty;

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

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

Hope helps,

Upvotes: 1

uzay95
uzay95

Reputation: 16622

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.

Upvotes: 1

sri harsha
sri harsha

Reputation: 682

You can try using like below

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

Upvotes: 3

Related Questions