The direct problem, as I see it, is you're binding that event to a button which is trying to cast sender to a text input. Because the sender becomes a button control and not a textbox, you'll receive the nullreferenceexception.
If you're looking for something click-related you have a few options:
- Hard-code a list of control you'd like to validate and refactor your check function to accept the control you're validating (in fact I would refactor this way anyways).
- [recursively] iterate over the controls within the form (using maybe this.Controls and passing the
Controls
property for each container element). Then, once again, pass these controls you find that you want to validate back to the validation method.
e.g.
// your validation method accepting the control
private void ValidateTextBox(TextBox textbox)
{
// validation code here
}
// bind to click event for button
private void btnValidate_Click(object Sender, EventArgs e)
{
// you can do manual reference:
List<TextBox> textboxes = new List<TextBoxes>();
textboxes.AddRange(new[]{
this.mytextbox,
this.mysecondtextbox,
...
});
//---or---
// Use recursion and grab the textbox controls (maybe using the .Tag to flag this is
// on you'd like to validate)
List<TextBox> textboxes = FindTextBoxes(this.Controls);
//---then---
// iterate over these textboxes and validate them
foreach (TextBox textbox in textboxes)
ValidateTextBox(textbox);
}
And to give you an idea of the recursive control grab:
private List<TextBox> FindTextBoxes(ControlsCollection controls)
{
List<TextBox> matches = new List<TextBox>();
foreach (Control control in collection)
{
// it's a textbox
if (control is TextBox)
matches.Add(control as TextBox);
// it's a container with more controls (recursion)
else if (control is Panel) // do this for group boxes, etc. too
matches.AddRange((control as Panel).Controls);
// return result
return matches;
}
}