davz_11
davz_11

Reputation: 145

Specified cast not valid

Can someone help me with this... i just simply can't locate where the error is... cause even I entered the right username and password a message pops up saying specified cast not valid

if (user_txt.Text != "" & pass_txt.Text != "")
{
    string queryText = "SELECT Count(*) FROM stiguidancesample.users " + "WHERE username = @Username AND password = @Password";
    MySqlConnection cn = new MySqlConnection(MyConnectionString);
    MySqlCommand cmd = new MySqlCommand(queryText, cn);
    {
        cn.Open();
        cmd.Parameters.AddWithValue("@Username", user_txt.Text);  // cmd is SqlCommand 
        cmd.Parameters.AddWithValue("@Password", pass_txt.Text);
        int result = (int)cmd.ExecuteScalar();
        if (result > 0)
            MessageBox.Show("Loggen In!");
        else
            MessageBox.Show("User Not Found!");
    }
}

Upvotes: 1

Views: 4380

Answers (1)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Problem : hee you need to remember that you are performing implicit casting using below statement:

int result = (int) cmd.ExecuteScalar();

the implicit casting only works if the value is valid integer.if it contains value like 10.0 or some spaces it wont work.

Solution : if you want to get the value in all of the caes you need to use Explicit casting using Convert.ToInt32() method.

Try This:

   int result = Convert.ToInt32(cmd.ExecuteScalar());

Upvotes: 5

Related Questions