我明白如何驗證事件與文本框工作,但我不明白它是如何觸發與表單上的按鈕。如何在Button類中使用Validating/Validated事件?
MSDN沒有驗證/驗證在documentation中列出。
但是,這兩個屬性在屬性窗口中都列爲事件。
我明白如何驗證事件與文本框工作,但我不明白它是如何觸發與表單上的按鈕。如何在Button類中使用Validating/Validated事件?
MSDN沒有驗證/驗證在documentation中列出。
但是,這兩個屬性在屬性窗口中都列爲事件。
您正在訪問MSDN的錯誤文檔頁面。你應該通過Button Events,在那裏你可以找到關於Validated和Validating事件的幫助。
每個
Control
派生的對象有兩個事件命名Validating
和Validated
。它也有一個名爲CausesValidation
的屬性。 當此設置爲true(默認情況下爲true),則控件 參與驗證。否則,它不會。
實施例:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the e-mail address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "e-mail address is required.";
return false;
}
// Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
if(emailAddress.IndexOf("@") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@"))
{
errorMessage = "";
return true;
}
}
errorMessage = "e-mail address must be valid e-mail address format.\n" +
"For example '[email protected]' ";
return false;
}
編輯:
Source:
上的WinForms驗證的最大問題是,當控制已經 「失去焦點」 的驗證是 僅執行。因此,用戶必須在文本框中實際點擊 ,然後在其他地方點擊 驗證例程來執行。如果您只關心輸入的數據是否正確 ,這很好。但是,如果你試圖確保用戶沒有跳過文本框 跳過它,這不起作用 。
在我的解決辦法中,當用戶點擊提交按鈕形式,我 檢查表單上的每個控件(或任何容器指定) 和使用反射來確定是否驗證方法是 控制定義。如果是,則執行驗證方法。如果 中的任何一個驗證失敗,則該例程返回一個失敗並允許該進程停止。此解決方案運行良好,特別是如果您有幾個表單需要驗證 。
參考文獻:
WinForm UI Validation
C# Validating input for textbox on winforms
可以使用驗證事件取消按鈕的動作,如果你的條件不符合而不是把這一行動在onClick事件放置在驗證的事件,而不是和。
它們在那裏列出是因爲它們是從Control
類繼承的。這裏是Validated,這裏是Validating。請注意,它們來自Control
。
有按鈕觸發驗證/驗證事件的一個簡單的方法?我只想看看這個事件是如何觸發的。我嘗試將按鈕和文本框之間的窗體和標籤放置在文本框中,但這些事件都沒有被觸發。 – Liger86 2013-04-11 14:19:23
請檢查參考鏈接,他們會幫助你在每一個可能的情況下.. – 2013-04-12 04:34:18
我已經檢查過他們,但發現很難理解。 – Liger86 2013-04-13 21:56:30