【问题标题】:textbox validated method does not work while assigning value to textbox为文本框赋值时,文本框验证方法不起作用
【发布时间】:2014-01-18 11:57:16
【问题描述】:

我正在使用 c#.net 2.0 winforms。我在表单中使用 errorprovider 控件来验证文本框。虽然我以编程方式为该文本框赋值。文本框验证方法不会从文本框中获取值或将其视为空白值。如何在文本框中不输入值来验证我的文本框。这是代码

private void textBox6_Validated(object sender, EventArgs e)
{
    bTest6 = txtRegExPinIsValid(textBox6.Text);
    if (bTest6)
    {
        this.errorProvider1.SetError(textBox6, "");
    }
    else
    {
        this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
    }
 }

 private bool txtRegExPinIsValid(string textToValidate)
 {
     Regex TheRegExpression;
     string TheTextToValidate;
     string TheRegExTest = @"^\d{6}$";
     TheTextToValidate = textToValidate;
     TheRegExpression = new Regex(TheRegExTest);
     // test text with expression 
     if (TheRegExpression.IsMatch(TheTextToValidate))
     {
         return true;
     }
     else
     {
         return false;
     }
  }

在执行更新操作时,我用 ms 访问表中的值填充文本框。如果值正确,请留下它,否则我必须更新它。请帮我。提前致谢

【问题讨论】:

  • 如果我手动将光标保留在每个文本框中并执行更新操作一切正常..

标签: winforms validation textbox c#-2.0


【解决方案1】:

我建议将验证代码放在单独的方法中。从Validated 事件和代码中您需要以编程方式验证的位置调用该方法,如下所示:

// Call this from wherever you need to validate a TextBox
void PerformValidation(TextBox textBox)
{
    bTest6 = txtRegExPinIsValid(textBox6.Text);
    if (bTest6)
    {
        this.errorProvider1.SetError(textBox6, "");
    }
    else
    {
        this.errorProvider1.SetError(textBox6, "This field must contain Exactly 6 digits");
    }
}

private void textBox6_Validated(object sender, EventArgs e)
{
    PerformValidation(textBox6);
}

【讨论】:

  • 谢谢布雷特!!你给了一个完美的解决方案。我找到了一个替代解决方案。将所有布尔值分配给“真”。我强制验证方法将文本框视为已验证,因为这些值是通过从表中查询以编程方式分配给文本框的。在更新操作时,如果我想更正文本框中的值,则会调用验证方法。否则我就离开它,因为 bool 值已经设置为 true。
猜你喜欢
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
相关资源
最近更新 更多