2016-04-24 45 views
1

我在一個c#winforms應用程序中使用errorprovider。 現在我想要進行「雙重」驗證。直接在文本字段上,以便用戶看到他犯了一些錯誤,並且一次在按鈕上。所以當仍有錯誤時,「保存」按鈕將保持灰色或「禁用」。錯誤提供程序c#winforms

因爲我不想在用戶發生錯誤時阻止用戶,並且我希望他能夠在需要使用事件「離開」或失去焦點時進行更改。這是因爲否則我發現你不能去另一個領域,直到你改變了你的錯誤。

所以,現在的代碼:

private void txtFirstname_Leave(object sender, EventArgs e) 
    { 
     if (!InputChecks.IsFilledIn(txtFirstname.Text)) 
     { 
      errorProvider1.SetError(txtFirstname, "Firstname needs to be filled in!"); 
      isValidated = false; 

     } 
     else 
     { 
      errorProvider1.SetError(txtFirstname, ""); 
      isValidated = true; 

     } 
    } 

到目前爲止,一切都很好。錯誤提供程序正常工作,我的用戶可以隨時編輯。

public void setSaveButton() 
    { 
     if (isValidated == true) 
     { 
      btnSave.Enabled = true; 

     } 
     else 
     { 
      btnSave.Enabled = false; 
     } 
    } 

bool isValidated; 
    private void btnSave_Click(object sender, EventArgs e) 
    { 

     if (isValidated == true) 
     { 

      employeePresenter.addEmployee(txtFirstname.Text, txtLastname.Text, txtUsername.Text, txtPassword.Text); 
     } 



    } 

這在我的腦海裏依然如此。但是,由於我可以讓用戶隨時更改問題,因此這種方式無效。我試圖把「setSaveButton()」方法放在「isvalidated」之下,但這也不起作用。由於焦點丟失。

任何人有更好的想法呢?我一直在尋找谷歌,我發現的唯一的事情是與errorprovider單個驗證,或事件驗證。但是這些事件不允許用戶隨時編輯他們的錯誤。它將它們阻塞到一個特定的文本字段中。

+0

此ValidateChildren()函數如何工作?因爲微軟網站上的例子並不十分清楚。它實際上不工作,所以我必須做錯事... https://msdn.microsoft.com/en-us/library/ms158374(v=vs.110).aspx – Kevin

+1

不得不猜測「它不工作「,你可能從未在你的Validating事件處理器中設置e.Cancel = true。所以ValidateChildren()方法不知道任何事情都沒有驗證。另一種方法是計算顯示的數字或錯誤圖標,請考慮使用[this class](http://stackoverflow.com/a/2682478/17034)。 –

+0

漢斯,「不起作用」有點不客氣。我實際上設置了e.cancel,但後來我再次將我的用戶鎖定到一個文本框中。在我的論壇中,這不是那麼用戶友好。我面臨的問題是我從來沒有進入else操作符。換句話說,我從來沒有「驗證失敗」。 – Kevin

回答

1

您不需要禁用保存按鈕。檢查ValidateChildren表單的方法就足夠了,如果它返回false,則意味着有一些驗證錯誤。要使用這種方法,您應該記得在爲控件設置錯誤時在控件的Validating事件中設置e.Cancel = true

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

代碼驗證:

private void txtFirstname_Validating(object sender, CancelEventArgs e) 
{ 
    if (string.IsNullOrEmpty(this.txtFirstname.Text)) 
    { 
     this.errorProvider1.SetError(this.txtFirstname, "Some Error"); 
     e.Cancel = true; 
    } 
    else 
    { 
     this.errorProvider1.SetError(this.txtFirstname, null); 
    } 
} 

private void btnSave_Click(object sender, EventArgs e) 
{ 
    if (this.ValidateChildren()) 
    { 
     //Here the form is in a valid state 
     //Do what you need when the form is valid 
    } 
    else 
    { 
     //Show error summary 
    } 
} 

也讓用戶即使有錯誤控件之間移動,在設計或使用代碼的FormAutoValidate屬性設置爲EnableAllowFocusChange