2011-02-23 133 views
0

我正在創建一個C#窗口應用程序,其中我採取了10個文本框。我想驗證每個文本框意味着沒有任何文本框應該是空白的。我已經使用errorprovider控件進行驗證點擊提交按鈕。 該代碼正常工作,但我想刪除錯誤提供程序通知一旦我插入空白文本框中的值。如何可能請通過任何示例給我的代碼。多個文本框的驗證

在此先感謝。

回答

0

根據您的實現,在文本框更改事件上,您可以調用您的文本框驗證/驗證事件處理程序,它將根據您在驗證/驗證處理程序中實現的任何邏輯設置或清除錯誤。

0

通常情況下,驗證應該發生在焦點離開文本框時 - 您的驗證事件是在這裏被解僱嗎?請參閱this MSDN documentation中的示例部分,瞭解如何結合使用驗證和驗證事件來獲得此權限。

由於你有很多這樣的文本框,我會建議你在裏面創建自定義文本框控件封裝驗證邏輯。

1

正確的做法是爲每個TextBox控件處理Validating event。對於您描述的場景,似乎沒有任何理由使用ValidatingValidated

因此,維奈所暗示的,最好的事情將是封裝這個代碼到從繼承的自定義控制內置TextBox。覆蓋自定義控件的OnValidating method,並將您的驗證邏輯置於/清除ErrorProvider。然後將您的表單上的每個文本框控件替換爲您的自定義類的實例,而不是內置的實例。

如果你真的驗證身份,只要在文本框中輸入文本進行更新,你需要處理TextChanged事件並調用你的驗證代碼來設置/清除ErrorProvider。覆蓋您的自定義控件中的OnTextChanged method以執行此操作。

1

這是我使用的代碼。你可以看到有2個處理程序,一個用於驗證,另一個用於TextChanged事件。 DataTextBox在工具箱中顯示爲一個圖標,因此您可以通過鼠標放置它,並且您還可以在屬性窗口中設置canBeEmpty屬性,默認值爲true。

public class DataTextBox:TextBox 
{ 
    public DataTextBox() 
    { 
     this._errorProvider2 = new System.Windows.Forms.ErrorProvider(); 
     //this.errorProvider1.BlinkRate = 1000; 
     this._errorProvider2.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink; 

     this.TextChanged+=new EventHandler(dtb_TextChanged); 
     this.Validating += new System.ComponentModel.CancelEventHandler(this.dtb_Validating); 


    } 
    private ErrorProvider _errorProvider2; 

    private Boolean _canBeEmpty=true; 
    public Boolean canBeEmpty 
    { 
     get { return (_canBeEmpty); } 
     set { _canBeEmpty = value; } 
    } 

    private void dtb_Validating(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     if ((this.Text.Trim().Length == 0) & !this.canBeEmpty) 
     { 
      _errorProvider2.SetError(this, "This field cannot be empty."); 
      e.Cancel = true; 
     } 
     else 
     { 
      _errorProvider2.SetError(this, ""); 
      e.Cancel = false; 
     } 
    } 

    private void dtb_TextChanged(object sender, EventArgs e) 
    { 
     if (this.Text.Trim().Length != 0) _errorProvider2.SetError(this, ""); 
     else _errorProvider2.SetError(this, "This field cannot be empty."); 
    } 
} 

}