0

I want to validate form input data using a database as data source. I have the following function which runs but when I input wrong or corect data it throws an error.

private void btnLogin_Click(object sender, EventArgs e)
{
    if (txtPassword.Text != "" && txtUsername.Text != "")
    {
        string queryText =
            "SELECT Count(*) FROM dbo.ClientLogin" +
            "WHERE ClientUserName = @uername AND ClientPassword = @password";

        SqlConnection scon = new SqlConnection(
            "Data Source=localhost;Initial Catalog=Clients;Integrated Security=True");
        SqlCommand command = new SqlCommand(queryText, scon);
        scon.Open();
        command.Parameters.AddWithValue("@username", txtUsername.Text);
        command.Parameters.AddWithValue("@password", txtPassword.Text);
        string result= Convert.ToString(command.ExecuteScalar());
        if (result.Length > 0)
        {
            frmMenu frmMenu = new frmMenu();
            frmMenu.ShowDialog();
        }
        else
            MessageBox.Show("User not found");
    }
    else
        MessageBox.Show("Enter username & password");
}

The error is:

SqlException was unhandled

for statement:

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

Any help on fixing this error will be appreciated. :)

3
  • 3
    You've got misspeling in parameter: @uername. Check the query code. Commented May 11, 2014 at 18:55
  • I fixed the misspelled word but it still gives the same error Commented May 11, 2014 at 19:08
  • 2
    So look for the inner exception. Commented May 11, 2014 at 19:10

1 Answer 1

1

If no user is found, then a count of 0 will be returned. Since you convert this int result into the string "0" its length will be 1. "0".Length == 1!

Since an int result is returned by ExecuteScalar() (statically typed as object), cast it to an int instead of converting it to a string:

int result = (int)command.ExecuteScalar();
if (result > 0) {
   ...
} else {
   ...
}

Also, as Volodymyr Melnychuk has already pointed out, the parameter in the SQL string should be called @username instead of @uername.


You are missing a space between dbo.ClientLogin and WHERE.

Replace

string queryText = "... dbo.ClientLogin" +
    "WHERE ...";

by

//                 see the space here  v
string queryText = "... dbo.ClientLogin " +
    "WHERE ...";

Other possible reasons: The table name is incorrect, the table is not in the dbo schema, a column name is incorrect, you don't have the required access rights.

Sign up to request clarification or add additional context in comments.

2 Comments

I have done as you and @ Volodymyr Melnychuk suggested but it still gives an error
Ya actually I didnt put a space in between table name and WHERE, it works now, thanks for both your help

Your Answer

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