【问题标题】:Textbox validation in a Windows FormWindows 窗体中的文本框验证
【发布时间】:2011-05-11 06:33:22
【问题描述】:

我想验证用户在提交表单之前总是在文本框中输入一个值。但是我所做的检查允许用户输入空格并继续提交表单。 那么,如果文本框中只有空格,如何进行检查以使用户无法提交表单。

【问题讨论】:

  • 您已经标记了问题 winforms,但听起来好像您在询问 webforms。是哪个?

标签: c# .net winforms textbox validation


【解决方案1】:

您可以制作自己的自定义验证函数。这可能很幼稚,但不知何故它会起作用。

private bool WithErrors()
{
    if(textBox1.Text.Trim() == String.Empty) 
        return true; // Returns true if no input or only space is found
    if(textBox2.Text.Trim() == String.Empty)
        return true;
    // Other textBoxes.

    return false;
}

private void buttonSubmit_Click(object sender, EventArgs e)
{
    if(WithErrors())
    {
        // Notify user for error.
    }
    else
    {
        // Do whatever here... Submit
    }
}

【讨论】:

    【解决方案2】:

    在NET4.0中有一个不错的功能

     if(string.IsNullOrWhiteSpace(textBox1.Text))
    {
       //raise your validation exception
    }
    else {
      //go to submit
    }
    

    【讨论】:

      【解决方案3】:

      使用错误提供程序可以很容易地完成,这里是代码。错误提供程序您可以在您的工具箱中找到。

          private void btnsubmit_Click(object sender, EventArgs e)
                  {
      
                      if (string.IsNullOrEmpty(txtname.Text))
                      {
      
                          txtname.Focus();
                          errorProvider1.SetError(txtname, "Please Enter User Name");
                      }
      
                      if (string.IsNullOrEmpty(txtroll.Text)) {
                          txtroll.Focus();
                          errorProvider1.SetError(txtroll, "Please Enter Student Roll NO");
                      }
      }
      

      这是输出图像

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2011-08-24
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多