Question

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. :)

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top