2014-11-09 42 views
2

我需要隐藏提交,但是如果在验证中有任何错误。我正在使用下面的代码,如果我输入了两个带有字符的文本框,并且如果我更正了文本框中的提交按钮,就会看到!如何避免它util所有的错误是明确的? 谢谢如果验证中有任何错误,请禁用提交按钮

int num; 

private void textBox5_TextChanged(object sender, EventArgs e) 
{ 
    bool isNum = int.TryParse(textBox5.Text.Trim(), out num); 
    if (!isNum) 
    { 
     button2.Visible = false; 
     errorProvider1.SetError(this.textBox5, "Please enter numbers"); 
    } 
    else 
    { 
     button2.Visible = true; 
     errorProvider1.SetError(this.textBox5, ""); 
    } 
} 

private void textBox6_TextChanged(object sender, EventArgs e) 
{ 
    bool isNum = int.TryParse(textBox6.Text.Trim(), out num); 
    if (!isNum) 
    { 
     button2.Visible = false; 
     errorProvider2.SetError(this.textBox6, "Please enter numbers"); 
    } 
    else 
    { 
     button2.Visible = true; 
     errorProvider2.SetError(this.textBox6, ""); 
    } 
} 

回答

1

检查两个文本框按钮可视性设置为True前无差错。您可以使用另一种方法,如下所示,使用UpdateSubmitButton

该方法检查textBox5textBox6是否存在与其相关的错误,然后相应地更新button2的可见性。请注意,我从TextChanged事件中删除了其他分配,并将其替换为对UpdateSubmitButton方法的调用。

private void UpdateSubmitButton() 
{ 
    if (String.IsNullOrEmpty(errorProvider1.GetError) && 
     String.IsNullOrEmpty(errorProvider2.GetError)) 
    { 
     button2.Visible = true; 
    } 
    else 
    { 
     button2.Visible = false; 
    } 
} 

private void textBox5_TextChanged(object sender, EventArgs e) 
{ 
    int num; 
    bool isNum = int.TryParse(textBox5.Text.Trim(), out num); 
    if (!isNum) 
    { 
     errorProvider1.SetError(this.textBox5, "Please enter numbers"); 
    } 
    else 
    { 
     errorProvider1.SetError(this.textBox5, ""); 
    } 
    UpdateSubmitButton(); 
} 

private void textBox6_TextChanged(object sender, EventArgs e) 
{ 
    int num; 
    bool isNum = int.TryParse(textBox6.Text.Trim(), out num); 
    if (!isNum) 
    { 
     errorProvider2.SetError(this.textBox6, "Please enter numbers"); 
    } 
    else 
    { 
     errorProvider2.SetError(this.textBox6, ""); 
    } 
    UpdateSubmitButton(); 
} 
+0

“System.Windows.Forms.TextBox”不包含“GetError”和没有扩展方法定义的所有TextChanged事件的这种方法“GetError”接受第一可以找到'System.Windows.Forms.TextBox'类型的参数 – JIMMY 2014-11-09 07:31:35

0

根据您验证文本框的数量,你可以创建一个一次性验证一切功能。

bool ValidateAll(){ 
    bool isNum = int.TryParse(textBox5.Text.Trim(), out num); 
    if (!isNum) 
    { 
     return false; 
    } 

    isNum = int.TryParse(textBox6.Text.Trim(), out num); 
    if (!isNum) 
    { 
     return false; 
    } 
    return true; 
} 

然后调用要监视

相关问题