In my project , the first form is the Login form and it appears only one time for the user when he attempt to login the system .. If the login is successful then a main form of the system appears and login form hides , if login attempt is failed then the user may try another time and so on ..
The problem is when the user in the main form want to close the program using the X button the message of Login form of FormClosing event appears it logout in the case of user pressed Yes ,but when the user press NO the program do not close but it returns to login form which is hidden
The codes for FormClosing event in Login Form are:
private void LoginFrm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult logoutResult = MessageBox.Show("Do you want to logout?","Logout",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (logoutResult == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
Now the same FormClosing event is happening for both Login form and main form how to make the program do nothing in case of the user pressed NO in logout messageBox and stay on its current situation and once the user login to system the Login form closes not hide .. regards
If you don't want to show the messageBox on LoginFrm_FormClosing when everything is closing:
private void LoginFrm_FormClosing(object sender, FormClosingEventArgs e)
{
//Add this lines, your login form is hidden
if (this.Visible == false)
{
return;
}
DialogResult logoutResult = MessageBox.Show("Do you want to logout?","Logout",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (logoutResult == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false; //<- you dont need this
}
}
And in MainForm:
//Add this line
Boolean isClosed = false; //<--
private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
{
//Add this
if(isClosed == true){
return;
}
DialogResult res = MessageBox.Show("Do you want to exit?");
if (res == DialogResult.OK) {
try {
SqlCommand cmd = new SqlCommand("delete from empLogin where empId=" + deleteById + "", cn);
cmd.ExecuteNonQuery();
//Add this line
isClosed = true; //<--
Application.Exit();
}
catch (SqlException ex) {
MessageBox.Show(ex.Message);
}
finally { cn.Close(); }
}
}