How do I display a error message if login fail for windows form-Collection of common programming errors
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();
}
}