2015-10-12 47 views
0

如何在WinForms中存在錯誤時顯示消息框「數據無效」。 試過類似的東西,但它不起作用。使用驗證事件和ErrorProvider進行驗證 - 顯示錯誤摘要

if (errorprovider1 == !null) 
{ 
MessageBox.Show("Data is invalid"); 
} 

也許我必須爲此解決方案使用bool。

我全碼:

private void Form1_Load(object sender, EventArgs e) 
{ 
    this.Text = "Formas elementu validācija"; 
} 

    private void textBox1_Validating(object sender, CancelEventArgs e) 
    { 
     Regex regex1 = new Regex(@"^[a-zA-Z]+$"); 
     if (!regex1.IsMatch(textBox1.Text)) 
     { 
      errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!"); 
     } 
     else 
     { 
      errorProvider1.Clear(); 
     } 
    } 

    private void textBox2_Validating(object sender, CancelEventArgs e) 
    { 
     Regex regex1 = new Regex(@"^[0-9]+$"); 
     if (!regex1.IsMatch(textBox2.Text)) 
     { 
      errorProvider2.SetError(textBox2, "Reģ.nur drīkst saturēt TIKAI ciparus!"); 
     } 
     else 
     { 
      errorProvider2.Clear(); 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     // if errorProvider1 is empty (no errors) , show messagebox with text: All data correct. 
     // else Data is incorrect. 
    } 
+0

如果您對解決方案有任何疑問,請告知我們。另外,當您找到有用的答案時,您可以點擊問題附近的複選標記以接受答案。您只能接受一個答案,而您可以投出儘可能多的答案,因爲您可以找到有用的答案,包括通過點擊向上箭頭接受答案。這樣你使答案更有幫助。你也可以爲好問題投票。 :) –

回答

2

你應該先糾正你的驗證事件是這樣的:

private void textBox1_Validating(object sender, CancelEventArgs e) 
{ 
    Regex regex1 = new Regex(@"^[a-zA-Z]+$"); 
    if (!regex1.IsMatch(textBox1.Text)) 
    { 
     //To set validation error 
     errorProvider1.SetError(textBox1, "Nosaukums nedrīskt saturēt ciparus!"); 
     //To say the state of control in invalid 
     e.Cancel = true; 
    } 
    else 
    { 
     //To clear the validation error 
     this.errorProvider1.SetError(this.textBox1, ""); 
    } 
} 

那麼你應該使用ValidateChildren方法來檢查是否有驗證錯誤或沒有,那麼你可以得到所有錯誤的清單並以這種方式向用戶顯示:

private void button1_Click(object sender, EventArgs e) 
{ 
    if (this.ValidateChildren()) 
    { 
     //Here the form is in valid state 
     //Do what you need when the form id valid 
    } 
    else 
    { 
     var listOfErrors = this.errorProvider1.ContainerControl.Controls.Cast<Control>() 
           .Select(c => this.errorProvider1.GetError(c)) 
           .Where(s => !string.IsNullOrEmpty(s)) 
           .ToList(); 
     MessageBox.Show("Please correct validation errors:\n - " + 
      string.Join("\n - ", listOfErrors.ToArray()), 
      "Error", 
      MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 

樣本屏幕截圖:

enter image description here

注:

  • 你不應該使用錯誤提供商Clear方法來設置有效狀態來控制,你應該使用SetError,例如this.errorProvider1.SetError(textBox2, "");
  • 如果存在驗證錯誤,您應該致電e.Cancel=true
  • 在示例代碼中,我假設您的所有控件(包括錯誤提供程序)都直接放在窗體上,而不是放在容器控件中。
  • 我還建議在設計時通過代碼形式的AutoValidate屬性設置爲EnableAllowFocusChangeLoad事件形式的這種方式改變形式的驗證行爲:

要改變形式的驗證行爲:

this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;