14
votes

This is a winform C# question. I have a textbox with a validating event listener to validate the content of the textbox against a regular expression.

After the validation, if entered value is not proper,i am showing the messagebox and i am cancelling the event so that mouse cursor move back to the textbox which has improper value.

This is working fine when i move out from that textbox to other buttons/textboxes.

But when i enter improper value and close the form (with the close button on right top corner), it validates the textbox contents and throws up the messagebox and form doesnot close as i am cacelling the event.

The problem is, when I click the X button on the right top corner of the form, I don't want the validation to be fired because I am closing the form anyway. How can I do this?

I will post the code snippet as soon as possible.

10
Maybe this answer: stackoverflow.com/a/25479010/1586914 could helps?Adiono

10 Answers

19
votes

To use validating handlers such as the 'txtIPAddress_Validating()' handler below while being able to close the form without having to enter valid entries to do so, I do the following:

1) Initate validating handlers: From the control properties of the control you wish to activate validation for, double click the 'Validating' event from this control event list. A control event list is accessed by clicking this control's property sheet’s event (lightning looking) toolbar button. You can then enter the code in the automatically generated handler with a name combining both the name of the control and '_Validating'. The part of this handler where something is established as invalid can force valid entries by adding the 'e.Cancel = true' instruction.

For such validating method examples, See 'txtIPAddress_Validating()' and 'txtMaskBits_Validating()' code below. Do not get distracted by the complete validation mechanism of these specific examples. All you need to see and reproduce in your own code in order to force validation is to add the 'e.Cancel = true' instruction at the right place of your own validating method. That is when the value is identified to be invalid.

At this point the validation should work fine but any attempt to close the form will trigger validation which will stop and insist for valid values before being able to close the form. This is not always what you want. When it is not so, I continue with the following.

2) 'Cancel' button that also cancels (disables) all validations:

a) Place a regular 'Cancel' button on the form which is associated to a method such as the 'btnCancel_Click()' method below.

b) Before the regular 'this.close();' instruction, add the 'AutoValidate = AutoValidate.Disable;' instruction. This instruction disables all 'validating' triggers. Note that the 'btnCancel_Click' event is triggered before any validation is taking place. That is not so for the Form Closing events that will all execute after validating events. That is why that validation cannot be disabled from any of these Form Closing events.

c) For this 'Cancel' button to work correctly, you also need to set the 'CausesValidation' property of this 'Cancel' button to 'false'. This is necessary, otherwise clicking on this button will trigger the validation before validating can be disabled by the above 'AutoValidate = AutoValidate.Disable;' instruction.

At this point, you should be able to quit by clicking on the 'Cancel' button without having to first enter valid values. However, clicking the upper right "X" button of the form's window will still force validation.

3) Make the upper right "X" button also cancel validation:

The challenge here is to trap such "X" clicked event before validation is executed. Any attempt to do so through a Form Closing handler will not work because it is then too late once execution reaches such handler. However, the click of the "X" button can be captured promptly via overriding the WndProc() method and testing for a 'm.Msg == 0x10' condition. When that condition is true, the previously introduced 'AutoValidate = AutoValidate.Disable;' instruction can again be used to disable overall validation in that case as well. See the WndProc() method below for a code sample of such method. You should be able to copy and paste that method as is in your form's class.

At this point, both the 'Cancel' an "X" buttons should cancel valdations. However, the escape key that can be used to close a form does not. Such escape key is activated when the form's 'CancelButton' property is used to link this escape key to the form's 'Cancel' button.

4) Make the escape key also cancel validation:

Similar to the "X" button, the escape key can be captured by overriding an existingmethod. That is the ProcessDialogKey() method. One more time, the previously introduced 'AutoValidate = AutoValidate.Disable;' instruction can be used to disable overall validation for the escape key as well. See the ‘ProcessDialogKey()’ overridden method in the code below to see how this can be done. Here again, you should be able to copy and paste that method as is in your own form's class.

At this point you should be done!

Further considerations:

It is good to notice that the following two other ways to close the window should also work fine at this point. These two ways are:

  • The 'Close' option of the upper left window icon button.
  • Pressing Alt+F4 which triggers the same closing action as the above 'Close' option.

These two ways of closing the window started to also cancel validation once you introduced the "X" button capture mechanism described in point 3 above.

That is it for me for this so far. Hoping this helps!

My code sample below:

public partial class frmMyIP : Form
{
    public frmMyIP()
    {
          InitializeComponent();
    }

    // To capture the Upper right "X" click
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x10) // The upper right "X" was clicked
        {
            AutoValidate = AutoValidate.Disable; //Deactivate all validations
        }
        base.WndProc(ref m);
    }

    // To capture the "Esc" key
    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Escape)
        {
            AutoValidate = AutoValidate.Disable;
            btnCancel.PerformClick(); 
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
    public bool IsValidIP(string ipaddr)
    {
        string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"+
        @"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";

        Regex check = new Regex(pattern);
        bool valid = false;

        if (ipaddr == "")
        {
            valid = false;
        }
        else
        {
            valid = check.IsMatch(ipaddr, 0);
        }

        return valid;
    }

    private void txtIPAddress_Validating(object sender, CancelEventArgs e)
    {
        string address = txtIPAddress.Text;
        if (!IsValidIP(address))
        {
            MessageBox.Show("Invalid IP address!");
            e.Cancel = true;
        }
    }

    private void cmbMaskBits_Validating(object sender, CancelEventArgs e)
    {
        int MaskBitsValue = Convert.ToInt32(cmbMaskBits.Text);

        if (MaskBitsValue<1 || MaskBitsValue>30)
        {
        MessageBox.Show("Please select a 'Mask Bits' value between 1 and 30!");
        e.Cancel = true;
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        // Stop the validation of any controls so the form can close.
        // Note: The CausesValidation property of this <Cancel> button
        //       must also be set to false.

        AutoValidate = AutoValidate.Disable;
        this.Close();
    }
4
votes

Insert the following as the first line in the validation event of the textbox:

//Allow the form to be closed
if (this.ActiveControl.Equals(sender))
    return;

Since the close event of the form is triggering validation and since that would (typically at least) be the only form event that would trigger validation we can make the assumption that any form event triggering validation is the close event.

3
votes

The actual answer is ridiculously simple compared to all the suggestions here which involve hacks and extra superfluous code to undo something.

The "trick" is just to allow the focus to change and not fire validation from buttons on the form itself.

You can simply set two properties on the form:

MyForm.CausesValidation = false;
MyForm.AutoValidate = AutoValidate.EnableAllowFocusChange;

Et voila, form acts normal when you try to close it and validation still works following other inputs such as tab changing focus or mouse clicks.

2
votes
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    // Assume that X has been clicked and act accordingly.
}

Create a closing event, then simply cancel your validator.

1
votes

Try to set CauseValidation to false

or see here : How to skip Validating after clicking on a Form's Cancel button

Or try set this in formClosing event

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    // CauseValidation to false  or check 

}
1
votes

What you need is an implementation like the one described below, where it is assumed that you have a Save button and a Cancel button for the form:

    public Form1()
    {
        // Disable validation in constructor
        textBox.CausesValidation = false;
    }

    private void OnSaveClicked(object sender, EventArgs e)
    {
        textBox.CausesValidation = true;
        if (ValidateChildren())
        {
            //
            // Do saving of the form data or other processing here ....
            //
            Close();
        }
        //
        // Set validation to false, as user may press Cancel next
        //
        textBox.CausesValidation = false;
    }

    private void OnCancelClicked(object sender, EventArgs e)
    {
        Close();
    }
0
votes

Check which button has focus in the validation check. If cancel button (and in my case a clear button), override. This is an inner method I call from my cell validating event handler. (Just realized it was a C# question, but you can translate)

Private Sub validateCell(ByVal tagDesc As String, ByVal userInput As String, ByVal legalRegex As String, ByVal regexDesc As String, ByVal e As DataGridViewCellValidatingEventArgs)
    Dim match As Match = Regex.Match(userInput, legalRegex)
    Dim matches = match.Groups()
    Dim val = match.Value
    If val.Length = 0 Or userInput.Length > val.Length Then
        tagGrid.Rows(e.RowIndex).ErrorText = _
            tagDesc & " must match pattern:  " & regexDesc
        If Me.Cancel_Button.Focused Or Me.clearButton.Focused Then
            e.Cancel = False
            tagGrid.Rows(e.RowIndex).ErrorText = ""
        Else
            e.Cancel = True
            MsgBox(tagDesc & " must match pattern:  " & regexDesc, MsgBoxStyle.Critical)
        End If
    Else
        e.Cancel = False
        tagGrid.Rows(e.RowIndex).ErrorText = ""
    End If
End Sub
0
votes

I came here in search of a simple method to cause a form to close when a Validating event handler raises an exception, reports it, and needs to force the form to close. After reading this topic and numerous others, followed by an afternoon of experimenting, I have made several discoveries, and developed a simple hack to force the form to close.

First things first, though; I discovered that when a Validating event calls this.Close() the FormClosingEventArgs.Cancel flag passed into its From_Closing event procedure is set to TRUE, effectively causing the event to cancel itself. Conversely, a normal Close event receives a FormClosingEventArgs.Cancel flag set to FALSE.

Since the Close method on a form takes no arguments, there is no direct way to force the issue, giving rise to the need for a hack. This article discusses a number of such hacks, but I think mine is much simpler to implement.

The hack starts with a simple form level Boolean variable.

    bool _fExceptionIsFatal = false;

Other than defining a Form_Closing event handler, this is the only structural change required to the form.

The Form_Closing event is straightforward.

    private void From1_Closing ( object sender , FormClosingEventArgs e )
    {
        if (this.CausesValidation )
        {   // There is no sense repeating this procedure if another routine already did it.
            DisableValidation ( );
        }   // if (this.CausesValidation )          

        if ( _fExceptionIsFatal )
        {   // Cancel False == Allow form to close.
            e.Cancel = false;
        }   // if ( _fExceptionIsFatal )
    }   // From1_Closing

Though DisableValidation is implemented as a local method of the current form, the same thing could be accomplished by passing a Form reference into a library routine, since a Form is a Form, and its Controls collection is a Controls collection, period. Before long, I'll do so, along with implementing its inverse, to turn validation on again.

    private void DisableValidation ( )
    {
        foreach ( Control ctrl in this.Controls )
        {
            ctrl.CausesValidation = false;
        }   // foreach ( Control ctrl in this.Controls )

        this.CausesValidation = false;
    }   // DisableValidation

The fourth piece of the solution is equally straightforward; whenever you want to force the form to close, set _intValueAsInteger to TRUE before you call this.Close.

0
votes

Add below code to your form. You can close the form even the children controls are validating.

protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x10) // The upper right "X" was clicked
    {
        this.ActiveControl = null;
        this.AutoValidate = AutoValidate.Disable;
    }
    base.WndProc(ref m);
 }
0
votes

This question is pretty old but thought of adding the answer anyway:

In the form constructor:

this.FormClosing += Form1_FormClosing;

In the closing event handler (Make sure CausesValidation for the form is set to true to begin with. You could also check the textbox's CausesValidation property instead of the form's) :

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.CausesValidation)
    {
        DisableValidation();    
        this.Close();
    }
}

In the DisableValidation method, disable validation for the textboxes and the form (I am using 2):

private void DisableValidation()
{
    txtbox1.CausesValidation = false;
    txtbox2.CausesValidation = false;
    CausesValidation = false;
}