How to handle form closing events - c#

I am using Windows Forms in c# and have problems with how and when the the different forms (i have 2) should close and not. It is very annoying since i feel that i should be able to fix it. But here we go.
I have two forms, one MainForm that calls another form called ContactForm.
The MainForm:
private void btnAdd_Click(object sender, EventArgs e)
{
ContactForm frmContact = new ContactForm();
int index = lstCustomers.SelectedIndex;
//If a customer is selected, export data for the selected customer to ContactForm
if (index != -1)
{
frmContact.ContactData = customerMngr.GetCustomer(index).ContactData;
}
if (frmContact.ShowDialog() == DialogResult.OK) //Show the ContactForm object
{
//The user has chosen the OK button - add the new customer object
customerMngr.AddCustomer(frmContact.ContactData); //??
UpdateCustomerList();
}
if (frmContact.ShowDialog() == DialogResult.Cancel)
{
return;
}
}
And the form that is called:
OK button.
private void btnOK_Click(object sender, EventArgs e)
{
if (ValidateInput())
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
Cancel button:
private void btnCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to cancel and discard all data?", "Cancel input", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
When the OK button in the ContactForm is used i want it to close, which works. When i press the cancel button, and no (in the box that appears), i want the form to stay open with the input still intact. Right now it doesn´t work.
Any ideas?
/Martin

Your code is alright. I think the problem lies in your Cancel Button itself. By this I mean that you probably attached (by designer or somewhere in code) DialogResul.Cancel to your button btnCancel.DialogResul property. To fix this simply set it to DialogResult.None.
If I'm right this is what is closing your second form.
See MSDN for more information.

Related

Close button initiates main_load event

I have multiple forms in my WinForm application.
The first form (Form1) is used for authentication, while the second (Main) is used as main dashboard for the application that opens additional forms.
When I am in designer mode, I double click on the close button within the Main form to generate the closing event, but something weird occurs.
Instead of:
private void Main_FormClosing(object sender, FormClosingEventArgs e)
The event that the click generates is:
private void Main_Load(object sender, EventArgs e)
I don't understand why.
I've tried to type the method manually as shown bellow:
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialog = MessageBox.Show("Do you really want to quit?", "Exit", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
Application.Exit();
} else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
But its simply not linked to the close button.
Any ideas why?
You need to find and delete the event assignment for the Main form Close buttton's click event. That code is going to be in the Main.Designer.cs module. Look for all instances of this code:
this.FormClosing += ...
Delete that assignment (or those assignments, if more than one), then go back to the form designer, double-click the Main form's close button, and Visual Studio will create and take you to the method handler for the FormClosing event.
In the form constructor for Main() you can bind an event handler for the FormClosing event like so.
public Main()
{
// other startup tasks here
this.FormClosing += Main_FormClosing;
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
var dialogResult = MessageBox.Show("Do you really want to quit?", "Exit", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
e.Cancel = true;
return;
}
Application.Exit();
}

C# how to send a message from one form to other just before close the form?

I have a program where I want it to ask a confirmation before close. It's just a simple form with the question and a yes and a no buttons. How can I send the information of which button was clicked back to the main form? All solutions I found were for communication with both forms opened, but when choosing a button in the second for it will close. Any tips or ideas?
The second type of form you described is similar to the MessageBox… You can use its direct implementation as a dialog. Untested Example :
DialogResult dr = MessageBox.Show("Are you Sure?",
"Confirm Exit?",
MessageBoxButtons.YesNo);
if (dr==DialogResult.Yes)
{
// Do work If Yes
}else //if( dr == DialogResult.No)
{
// Do work if No
}
See MSDN for MessageBox
I tend to do it this way.
Code for child form:
private bool _bDoSomething=false;
public bool showForm()
{
this.ShowDialog();
return _bDoSomething;
}
private void btnOK_Click(object sender, EventArgs e)
{
_bDoSomething=true;
this.Hide();
}
And then this sort of code for the parent form:
dlgMyForm dlgMyForm = new dlgMyForm();
if (dlgMyForm.showForm())
{
//do something
}
Declare a boolean value in main form as public
public Boolean check =false;
In the second form's FormClosing event do the following
private void Form2_FormClosing(Object sender, FormClosingEventArgs e)
{
DialogResult answer = MessageBox.Show("[Your text]",MessageBoxButtons.YesNo)
if(answer == DialogResult.Yes)
{
Form1.check=True; //if button yes is clicked
// set the form1 check variable to True and closes form2
}
else
{
Form1.check=False; //if button no is clicked
// set the form1 check variable to False and cancel form
// closing
e.Cancel=True;
}
}
Use the boolean variable check to do further processing in form1

How to close entire application when application has more than 2 forms without showing messagebox more than once

I am developing a application using windows forms. The project contains 3 forms: one login form which is the main form and two others which are child forms to the login form.
My problem is when want to close the total application by using Application.Exit() in form closing event my messagebox showing the dialog more than once.
1.This code in Login form i.e main form:
private void FrmLogIn_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (loginResult == DialogResult.Yes)
{
Application.Exit();
}
}
2.AdminForm closing event which is child form to login form:
private void FrmAdmin_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (loginResult == DialogResult.Yes)
{
Application.Exit();
}
}
3.Billoperations form closing event which is child form to login form:
private void FrmBillOperation_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (loginResult == DialogResult.Yes)
{
Application.Exit();
}
}
When i click the close button in any form it will show MessageBox message only once. Please help me.
Make all FormClosing methods call a ApplicationShutdown function which handles this in a central place. You don't want to copy this code to every new form you create.
In this method you can check a boolean (watch for thread-safety) called for example IsShuttingDown. If it's already true, leave the method, otherwise you ask the question and start exiting.
The FormClosingEventArgs instance passed to the FormClosing event has a CloseReason property, which will be set to CloseReason.ApplicationExit when the Exit method of the Application class has been invoked: your handlers should check for this condition and if so then take no further action.
private void FrmLogIn_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExit)
return;
...
}
You can try with this code
FormCollection fc = Application.OpenForms;
if (fc!= null && fc.Count > 0)
{
for (int i = 1; i < fc.Count; i++)
{
if (fc!= null && fc.IsDisposed!= true)
{
fc.Dispose();
}
}
}
private void sh_interface_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (Form f in Application.OpenForms)
{
if (!f.IsDisposed)
f.Dispose();
}
}
else
{
e.Cancel = true;
this.Activate();
}
}
This will close all forms including the hidden forms and the main form from Application.Run(new something())...Also this method works when invoked in inherited classes while coded in template class Form Closing event.

Problems with events

I'm using a form with a OK and a Cancel button. When the user click on the Cancel button, the user will get a message to confirm if the form should close or not. A click on OK = close, but when click on Cancel, the form should not close, but thats what is happening right know, and I have tested to add some event code for the form, but still closing. What can I do to Get it to work properly?
// Button - Cancel
private void btnCancel_Click(object sender, EventArgs e)
{
// Message box to confirm or not
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
// Yes
//this.Close(); // Closes the contact form
m_closeForm = false;
}
else
{
m_closeForm = false;
// No
// Do nothing, the user can still use the form
}
}
private void ContactForm_Formclosing(object sender, FormClosingEventArgs e)
{
if (m_closeForm)
e.Cancel = false; // Stänger formuläret. Inget skall hända
else
e.Cancel = true; // Stänger inte formuläret
}
You can try the following, by adding the messagebox with the dialog result in the form closing event. I believe this is the better approach:
private void btnCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to cancel and discard all data?", "Think twice!",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
this.Close();
}
// Form wont close if anything else is clicked
}
private void btnOk_Click(object sender, EventArgs e)
{
// PerformAction()
this.Close();
}
I think this is what you are looking for.
I think you'll find that in your form's Designer.cs file you'll have the following line:
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
Remove this line and your form will no longer automatically close regardless of the result of your customer MessageBox.
To Cancel Closing you can use the FormClosingEventArgs Property, ie, e.Cancel to true.
Use this code in FormClosing Event of the Form.
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}

question about windows forms checkbox

private void frmSearch_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Year' table. You can move, or remove it, as needed.
this.dist_YearTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Year);
// TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Auth' table. You can move, or remove it, as needed.
this.dist_AuthTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Auth);
// TODO: This line of code loads data into the 'bookdatabaseDataSet.Book' table. You can move, or remove it, as needed.
this.bookTableAdapter.Fill(this.bookdatabaseDataSet.Book);
}
private void button1_Click(object sender, EventArgs e)
{
Form f4 = new Confirm();
f4.Show();
Hide();
}
private void button2_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Application.Exit();
}
}
my question is:
I want from the form to give me error message if I didn't check any of the check boxes. what is the correct code for it? and where should I right it? and thanks a lot for your concern.
form of windows application
For every checkbox do a checkbox.Checked test (boolean AND) and display a message box.
If you wanted to prevent the closing of the application then you have to handle the closing event and set CANCEL to true in this case.
void HandleFormClosing (object sender, CancelEventArgs args)
{
if (checkbox1.Checked && checkbox2.Checked)
return;
MessageBox.Show ("Need to check all boxes");
args.Cancel = true;
}
I guess you want to ensure at least one checkbox is checked when button1 is clicked, right? If so, place it at the beginning of button1_Click event.
private void button1_Click(object sender, EventArgs e)
{
if (!checkbox1.Checked && !checkbox2.Checked && !checkbox100.Checked)
{
MessageBox.Show("Please select a checkbox.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
checkbox1.Focus();
}
else
{
Form f4 = new Confirm();
f4.Show();
Hide();
}
}
This will not give you a direct answer (work-done-just-for-you kind of answer), but should point you in the right direction:
Finding the selected Radiobutton's value in ASP.NET
You can do this using custom validation.
But you could also get rid of the checkboxes and assume that if the user types in the textbox then they want to do a search on the field.
Start with search button disabled and only enable it when at least one field has text in it.

Categories