我正在使用c#.net 2.0 winforms。我在表单中使用errorprovider控件来验证文本框。虽然我以编程方式为该文本框分配值。 textbox验证方法不从文本框中获取值或将其视为空值。如何在不在文本框中输入值的情况下验证文本框。这是代码
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访问表中的值填充文本框。如果值正确,请保留,否则我必须更新它。请帮我。提前致谢
答案 0 :(得分:0)
我建议将验证代码放在一个单独的方法中。从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);
}