【问题标题】:Check for empty textboxes using C# function使用 C# 函数检查空文本框
【发布时间】:2011-04-09 14:39:33
【问题描述】:

我编写了一个函数来检查表单上的任何文本框是否为空白。 如果我将它添加到 TextBox 'leave' 事件,它目前可以工作。

我尝试将它添加到按钮单击事件中,但它给出了错误 (NullReferenceException unhandled)。

下面是代码:

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, "");
        }
    }

只是想知道您是否可以建议我如何解决它。

非常感谢。

【问题讨论】:

  • 错误的sender,它是一个Button,而不是一个TextBox。

标签: c# validation textbox


【解决方案1】:

您想验证 Windows 应用程序中的空文本框吗?最好在 Validating / Validate 事件中使用它。

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);
}

这些链接可能对您有所帮助

  1. Validating WinForms TextBox (in C#)
  2. WinForm UI Validation

【讨论】:

    【解决方案2】:

    在我看来,直接的问题是您将该事件绑定到一个按钮,该按钮试图将 sender 转换为文本输入。因为发送者变成了一个按钮控件而不是一个文本框,所以你会收到 nullreferenceexception。

    如果您正在寻找与点击相关的内容,您有几个选择:

    • 硬编码您要验证的控件列表并重构您的检查函数以接受您正在验证的控件(事实上,无论如何我都会这样重构)。
    • [递归地] 迭代表单中的控件(可能使用this.Controls 并为每个容器元素传递Controls 属性)。然后,再次将您发现要验证的这些控件传递回验证方法。

    例如

    // 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);
    }
    

    让您了解递归控制抓取:

    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;
      }
    }
    

    【讨论】:

      【解决方案3】:

      这样的事情怎么样:

      //This is a class property of the form itself. 
      public bool IsValid { get; set; }
      
      private void ValidateForm()
      {
          Action<Control.ControlCollection> func = null;
      
          func = (controls) =>
          {
              foreach (Control control in controls)
                  if (control is TextBox)
                      if (String.IsNullOrEmpty(control.Text))
                          this.IsValid = false;
                  else
                      func(control.Controls);
          };
      
          func(Controls);
      }
      

      您遍历控件,检查它是否是文本框,如果 .Text 为空,则将 IsValid 的类变量设置为 false。

      然后在单击按钮或某些东西时,表单的 .IsValid 为 false,触发错误。

      【讨论】:

        【解决方案4】:

        据我所知,这似乎是因为 sender 实例是 Button 而不是 TextBox,这就是您试图在以下行中所说的:

        userInput = sender as TextBox;
        

        这不起作用,因为您单击的按钮是触发事件的控件,因此该控件将成为发送者。

        既然TextBox 控件有(或至少应该有)一个预定义的名称/标识符,为什么不直接访问呢?如:

        theNameOfTheTextBox.Text
        

        【讨论】:

          猜你喜欢
          • 2013-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-10
          • 1970-01-01
          相关资源
          最近更新 更多