简体   繁体   中英

How do I display a error message if login fail for windows form

I have a form with username, password and login button. I have three tables called doctor, nurse and admin.

I want to display error message if login is unsuccessful when button is clicked.

Below is my login button code. I tried putting in codes in the catch (SqlException ex) recommended by another person but it has no effect when the login button is pressed.

private void btnLogin_Click(object sender, EventArgs e)
{
    //retrieve connection information info from App.config
    string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
    //STEP 1: Create connection
    SqlConnection myConnect = new SqlConnection(strConnectionString);
    //STEP 2: Create command
    string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
    // Add a WHERE Clause to SQL statement
    strCommandtext += " WHERE dUsername=@dname AND dPassword=@dpwd;";
    strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=@nname AND nPassword=@npwd;";
    strCommandtext += "SELECT windowsUsername, windowsPassword from WINDOWSADMIN WHERE windowsUsername=@aname AND windowsPassword=@apwd";
    SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
    cmd.Parameters.AddWithValue("@dname", textUsername.Text);
    cmd.Parameters.AddWithValue("@dpwd", txtPassword.Text);
    cmd.Parameters.AddWithValue("@nname", textUsername.Text);
    cmd.Parameters.AddWithValue("@npwd", txtPassword.Text);
    cmd.Parameters.AddWithValue("@aname", textUsername.Text);
    cmd.Parameters.AddWithValue("@apwd", txtPassword.Text);


    try
    {
        // STEP 3: open connection and retrieve data by calling ExecuteReader
        myConnect.Open();
        // STEP 4: Access Data
        SqlDataReader reader = cmd.ExecuteReader();


        while (reader.Read()) //For Doctor
        {
            if (MessageBox.Show("Login Successful") == DialogResult.OK)
            {
                timer1.Enabled = true;
            } 
        } 
        reader.NextResult();
        while (reader.Read()) //For Nurse
        {
            if (MessageBox.Show("Login Successful") == DialogResult.OK)
            {
                timer2.Enabled = true;
            }
        }

        reader.NextResult();
        while (reader.Read()) //For Admin
        {
            if (MessageBox.Show("Login Successful") == DialogResult.OK)
            {
                timer3.Enabled = true;
            }
        }



        //STEP 5: close connection
        reader.Close();
    }
    catch (SqlException ex)
    {
        string message = ex.Message;
        string caption = "Error Detected in Input";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result;

        // Displays the MessageBox.

        result = MessageBox.Show(message, caption, buttons);
    }
    finally
    {
        //STEP 5: close connection
        myConnect.Close();
    }
}

You're confusing logging into the SQL server to run the queries and using the queries to check a username / password combo. If the user can establish a connection to the server and execute the queries, the catch block will not be entered.

What you must do instead is maintain a variable that keeps track of whether or not the query returned a result.

For example:

bool recordFound = false;

while (reader.Read()) //For Doctor
{
    recordFound = true;
}

if (!recordFound)
{
    MessageBox.Show("Error in Input");
    return;
}

MessageBox.Show("Login Successful");
timer1.Enabled = true;

reader.NextResult();

Note that this is a bad way of maintaining passwords as anyone could easily use some other tool like SSMS to connect to your server and download the list of users and passwords. Without altering your design too much, a better option would be to use stored procedures to return a valid / invalid response when provided a username / password.

You need to insert 3 return; statements when login is successful.

timer1.Enabled = true;
return;

...

timer2.Enabled = true;
return;

...

timer2.Enabled = true;
return;

... and show the error message before closing the connection

MessageBox.Show("Invalid username or password");
//STEP 5: close connection

the code in catch block will only be executed when an Exception (which is a kind of runtime error) is thrown.

You can also try this:

    SqlDataReader reader = cmd.ExecuteReader();

        bool _doc, _nurse, _admin;

        while (reader.Read()) //For Doctor
        {
            _doc = true;
            timer1.Enabled = true;
            break;
        }

        reader.NextResult();

        while (reader.Read()) //For Nurse
        {
            _nurse = true;
            timer2.Enabled = true;
            break;
        }

        reader.NextResult();

        while (reader.Read()) //For Admin
        {
            _admin = true;
            timer3.Enabled = true;
            break;
        }

        reader.Close();

        if (!_doc && !_nurse && !_admin)
            MessageBox.Show("Unable to login for Doctor,Nurse and Admin.");
        else
            MessageBox.Show("Login successful for " + (_doc ? "Doctor" : string.Empty) + (_nurse ? ", Nurse" : string.Empty) + (_admin ? ", Admin" : string.Empty));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM