Here is a more complete treatment of this issue from another newsgroup:
Amazing. This must mean that the Form.Close() function is causing the validating textbox to regain focus. And, contrary to what one might assume from reading the docs, the CausesValidation property CAN effectively be applied to the control in which it is defined, and not just some other (second) control which was previously in focus.
For what its worth, you can use Validation and provide a clean form exit by
1) Add a Cancel button to your form
2) Set the Cancel buttons CausesValidation property to false
3) Add a click event handler for the button, and in this handler set all controls CausesValidation
properties to false. Then call this.Close(). As in:
------------
private void CancelButton_Click(object sender, System.EventArgs e)
{
minValueTextBox.CausesValidation = false;
maxValueTextBox.CausesValidation = false;
epMinTextBox.CausesValidation = false;
epMaxTextBox.CausesValidation = false;
this.Close();
}
------------
If you want the Close box on the title bar to be functional when there is a validation error, then you need to:
1) Add a Form Closing event handler, and in this handler set all controls CausesValidation
properties to false. Then set e.Cancel = false and you are done. As in:
-----------
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
minValueTextBox.CausesValidation = false;
maxValueTextBox.CausesValidation = false;
epMinTextBox.CausesValidation = false;
epMaxTextBox.CausesValidation = false;
e.Cancel = false;
}
-----------
If someone hits your Cancel button,you get a totally clean exit from the form. However, if the Close box on the title bar is pressed, they get a validation error THEN the form is closed.
Getting better than this will require a fix from MS or using Clays suggestion to set all controls CausesValidation properties to false when the WM_CLOSE message is detected.
Thanks Clay!
David
"ClayB [Syncfusion]" <clayb@syncfusion.com> wrote in message news:%23R1gNFoLDHA.3392@tk2msftngp13.phx.gbl...
> One way you can do this is to override your forms WndProc method and catch
> the click on the System Menus Close button, and then set the TextBoxs
> CausesValidation property false.
>
> public const int SC_CLOSE = 0xF060;
> public const int WM_SYSCOMMAND = 0x0112;
> protected override void WndProc(ref System.Windows.Forms.Message m)
> {
> if(m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
> {
> this.textBox1.CausesValidation = false;
> }
>
> base.WndProc(ref m);
> }
>
>
> ==================
> Clay Burch, .NET MVP
>
> Visit
www.syncfusion.com for the coolest tools
>
>