Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for empty textboxes using C# function

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.

like image 460
a.bell Avatar asked Aug 22 '26 23:08

a.bell


2 Answers

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

  1. Validating WinForms TextBox (in C#)
  2. WinForm UI Validation
like image 72
Anuraj Avatar answered Aug 25 '26 14:08

Anuraj


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;
  }
}
like image 26
Brad Christie Avatar answered Aug 25 '26 14:08

Brad Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!