2016-02-13 92 views
1

我有這樣的代碼做一些基本的理智張貼記錄前檢查:是否可以查詢ErrorProvider以查看是否設置了錯誤?

if (string.IsNullOrWhiteSpace(textBoxFirstName.Text)) 
{ 
    errorProvider.SetError(textBoxFirstName, "Enter a first name"); 
} 
if (string.IsNullOrWhiteSpace(textBoxLastName.Text)) 
{ 
    errorProvider.SetError(textBoxLastName, "Enter a last name"); 
} 

...但我想那麼做這樣的事情,退出處理程序,如果其中的任意一種條件已經得到滿足:

if (errorProvider.SetErrorCount > 0) then return; 

...但我看不出這樣做。我不想寫一個「OR」語句來查看我檢查的任何一個文本框是否爲空,然後以這種方式短路處理程序。

有沒有辦法判斷errorProvider是否「髒」以避免亂碼?

回答

2

編寫一個方法並將錯誤消息和控件傳遞給它。有一個計數器變量並增加該方法內的計數器。這裏有一些僞代碼:

private int errorCount; 
SetError(Control c, string message) 
{ 
    errorProvider.SetError(c, message); 
    errorCount++; 

} 
1

一個選項是從ErrorProvider中使用GetError方法。

// possibly use a backing field for all controls to evaluate 
private readonly Control[] textBoxes = new[] { textBoxFirstName, textBoxLastName }; 

// helper property to evaluate the controls 
private bool HasErrors 
{ 
    get { return textBoxes.Any(x => !string.IsNullOrEmpty(errorProvider.GetError(x)); } 
} 
+0

令人印象深刻的,MetroSmurf! –