form data validation

D

Dan

I have a question about form data validation and error providers: typically,
I add some controls and an error provider to my form, then I handle the
Validating event of each control which requires validation and perform the
data check. In this handler I use the error provider SetError and set
e.Cancel to true when a validation error is found, so that the user has to
correct his input before leaving the control.
All this is fine, my question is: if there are many controls requiring
validation in the form, and the user just fills one and then clicks the OK
button without even entering the other controls, their Validating events are
*not* fired: to avoid the form closing with invalid data, I should then
re-check each control data in the OK button handler. How can I do this
without having to duplicate the validation code (once in the Validating
handler and another time in the OK button click handler)? I'd need some way
of triggering all the Validating events for each control in the form
requiring validation...

Thanx in advance!
 
S

Sijin Joseph

In the Ok button event handler iterate through all the controls on the form
setting focus on them and then calling Form.Validate() that will
automatically call the validating event handlers for the controls

Check out this code from Windows Form Programming in C# by Chris Sells

// Retrieve all controls and all child controls etc.
// Make sure to send controls back at lowest depth first
// so that most child controls are checked for things before
// container controls, e.g., a TextBox is checked before a
// GroupBox control
Control[] GetAllControls() {
ArrayList allControls = new ArrayList();
Queue queue = new Queue();
queue.Enqueue(this.Controls);

while( queue.Count > 0 ) {
Control.ControlCollection
controls = (Control.ControlCollection)queue.Dequeue();
if( controls == null || controls.Count == 0 ) continue;

foreach( Control control in controls ) {
allControls.Add(control);
queue.Enqueue(control.Controls);
}
}

return (Control[])allControls.ToArray(typeof(Control));
}

void okButton_Click(object sender, EventArgs e) {
// Validate each control manually
foreach( Control control in GetAllControls() ) {
// Validate this control
control.Focus();
if( !this.Validate() ) {
this.DialogResult = DialogResult.None;
break;
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top