I have written a function to check if any textboxes on a form are blank. It currently works if I add it to the TextBox 'leave' event.
I tried adding it to a button click event but it gives an error (NullReferenceException unhandled).
Below is the code:
public void inputBlank(object sender, EventArgs e)
{
TextBox userInput;
userInput = sender as TextBox;
userTextBox = userInput.Text;
string blankBoxName = userInput.Name;
string blankBox = blankBoxName.Remove(0,3);
if (userTextBox == "")
{
errWarning.SetError(userInput, "Please enter a value for " + blankBox);
userInput.Focus();
}
else
{
errWarning.SetError(userInput, "");
}
}
Just wondering if you could advise me how to fix it.
Many thanks.
You want to validate an empty textbox in Windows application? Better to use it in Validating / Validate event.
private void sampleTextbox8_Validating(object sender, CancelEventArgs e)
{
TextBox textbox = sender as TextBox;
e.Cancel = string.IsNullOrWhiteSpace(textbox.Text);
errorProvider1.SetError(textbox, "String cannot be empty");
}
private void sampleTextbox8_Validated(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
errorProvider1.SetError(textbox, string.Empty);
}
These links may help you
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:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With