I have a form which, among the other controls, has a TextBox field that can be optionally filled by user .
There is also a btnSubmit Button that performs required actions and closes the form .
In its code, I check if a comment is present and, if not so, ask the user if he wants to fill it before exiting .
I use a bool AskToFillCommentIfNeeded() function that displays a MessageBox asking user to optionally fill the comment before exiting if this has not been done already .
It returns true if user answered Yes, false otherwise .
If user clicks Yes, I must exit the submit function without closing the form, so user can enter the comment and then press submit button again .
The [edited] code is something like this :
private void btnSubmit_Click(object sender, EventArgs e)
{
// ask user if he wants to fill the comment : if so, exit this function
if (AskToFillCommentIfNeeded()) { return; };
// ... save data and exit form ...
}
I use this code in a non modal form and it works as expected .
But when I try to use it in a modal form with btnSubmit DialogResult property set to OK,
it does not work as expected :
instead of just exiting the event sink, it closes the form
without saving data .
I made up a (clumsy) workaround, using a boolean flag like this :
private bool isBusy = false;
private void btnSubmit_Click(object sender, EventArgs e)
{
// clumsy attempt to avoid form exit :
isBusy = true;
// ask user if he wants to fill the comment : if so, exit this function
if (AskToFillCommentIfNeeded()) { return; };
isBusy = false;
// ... save data and exit form ...
}
Thus, if the return statement is executed, I intercept the _FormClosing event and cancel it if the flag is set to true :
private void FDialog_FormClosing(object sender, FormClosingEventArgs e)
{
// abort closing if flag is set
e.Cancel = isBusy;
}
This works, but it is less than satisfactory .
Is there a better way to achieve the same behaviour ?
I am using C# Express 2010 .
Thank you in advance .
jack griffin
Just set the form's DialogResult property back to None to prevent the dialog from closing:
private void btnSubmit_Click(object sender, EventArgs e)
{
if (AskToFillCommentIfNeeded()) {
this.DialogResult = DialogResult.None;
return;
}
// ... save data and exit form ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With