I'd like to make the following a generic method that all my forms can call to
validate all the fields on the form. So how do I pass the form object that
is represented as "this" in the following code, and how do I retrieve the
list of all controls and child controls on that form (since I don't think I
can just refer to Controls).
#region AnyFieldErrors
private bool AnyFieldErrors()
{
// Clear the error message fields
bool _anyErrors = false;
// Perform the validate event for each field on the screen
foreach (Control control in GetAllControls() )
{
if (control.CausesValidation == true)
{
control.Focus();
this.Validate();
}
}
// Check the properties for the custom fields to see if has errors.
foreach (Control control in GetAllControls() )
{
if (control.CausesValidation == true)
{
control.Focus();
string CName = control.Name;
string CType = control.GetType().ToString();
switch (CType)
{
case "WS.Windows.Forms.NameTextBox":
if (((WS.Windows.Forms.NameTextBox)control).InvalidDa ta)
{
_anyErrors = true;
}
break;
} // end switch Ctype
} // endif control.CausesValidation
} // end for each
return _anyErrors;
} // end Method
// Retrieve all controls and all child controls and 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 list = new ArrayList();
GetAllControls(Controls, list);
return (Control[])list.ToArray(typeof(Control));
}
void GetAllControls(Control.ControlCollection controls, ArrayList list)
{
foreach(Control control in controls)
{
if(control.HasChildren)
GetAllControls(control.Controls, list);
list.Add(control);
}
}
#endregion