validation & closing form bug

  • Thread starter Thread starter Andrew
  • Start date Start date
A

Andrew

- There is a form, which contains a user control.
- This control contains another control.
- The OnValidating method of the second control is
overridden. So there are some situations when control is
not valid:
protected override void OnValidating( CancelEventArgs e )
{
if ( ... )
{
e.Cancel = true;
MessageBox.Show( "Validation error!" );
}

base.OnValidating( e );
}
- But when user tries to close the form, it closes after
showing message box. This is not correct. The form
shouldn't be closed. Is this a framework bug?

Thank you.
 
- But when user tries to close the form, it closes after
showing message box. This is not correct. The form
shouldn't be closed. Is this a framework bug?

Omit the call to:
base.OnValidating( e );

You do not want default behaviour, you want to modify the default behaviour.
HTH,

Ian Cooper
wwww.dnug.org.uk
 
Hi Andrew,

1. Ensure you do not remove controls programmatically. If you do, ensure the
OnControlRemove call is in place.

2. I've also heard you should reset all validation errors before an attempt
to close a form.
 
Hi Andrew,
This doesn't help.
I tested this as follows but cannot recreate your behavious. I created a user control project which is just stripped down to a:
A user control containing only a textbox.
A Validating event handler for the user control that just sets the CancelEventArgs to true and displays a message
private void UserControl1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true ;
MessageBox.Show("Not valid") ;
}
I then created a new Windows Form App and added an instance of this user control to a form along with a close button:
private void btnSubmit_Click(object sender, System.EventArgs e)
{
this.Close() ;
}

This works as expected. The message box is thrown and validation returns the focus to the user control without closing the form.
For good measure I tried putting the Validating handler on the textbox on the user control:
private void txtBoxInner_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true ;
MessageBox.Show("Text Box Not valid") ;
}

This just displayed that message instead, but still behaved as expected.
For good measure I took the validating routines off the control and put the validating routines on the form:
private void userControl11_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true ;
MessageBox.Show("On Form Validating failed") ;
}

Still get the expected behaviour. Maybe I have missed something in your description. Any clues?
Do you want me to send you my skeleton test application?
Ian Cooper
wwww.dnug.org.uk
 
Back
Top