[英]Error message to show which text boxes are blank C#
嘿,所以我所有的代碼都可以正常工作了。 但是我想稍微清理一下。
目前,我只顯示一個消息框,顯示輸入中是否有錯誤,因此它將顯示“請檢查您的輸入”,但是我希望它顯示類似“請檢查以下內容:名字,名字等”的信息。 。”
if ((FirstnameText.Text.Trim().Length == 0) || (SurnameText.Text.Trim().Length == 0)
|| (DateOfBirthText.Text.Trim().Length == 0) || (CourseText.Text.Trim().Length == 0)
|| (MatricNoText.Text.Trim().Length == 0) || (YearMarkText.Text.Trim().Length == 0)
|| (int.Parse(MatricNoText.Text) < 10000 || int.Parse(MatricNoText.Text) > 99999)
|| (int.Parse(YearMarkText.Text) < 0 || int.Parse(YearMarkText.Text) > 100))
{
errorMessage();
return;
}
public void errorMessage()
{
MessageBox.Show("Please check your input");
}
我知道這很亂,但是嘿,它有效
當前它只是輸出該消息,是否有一種簡單的方法來輸出具有錯誤的特定文本框?
謝謝
內置的ErrorProvider組件將根據您的情況提供奇跡。 將其從工具箱拖動到表單的設計器上。 它會顯示在底部的NotificationIcons和ContextMenuStrips底部。 ErrorProvider的優點在於,它提供了一個視覺反饋圖標,並帶有鼠標懸停在控件旁邊的工具提示上。
然后,您可以使用控件的“ Validating”事件來檢查所需內容:
private void FirstnameText_Validating (object sender, CancelEventArgs e)
{
string error = null;
if (FirstnameText.Text.Length == 0)
{
error = "You must enter a First Name";
e.Cancel = true; // This is important to keep focus in the box until the error is resolved.
}
ErrorProvider.SetError((Control)sender, error); // FirstnameText instead of sender to avoid unboxing the object if you care that much
}
您也可以將其粘貼在“保存”按鈕中,而不是在“驗證”事件中引發它。 為了進一步清理代碼,請創建一個類來驗證輸入,以將非UI內容排除在UI外。
拆分代碼將是一個開始:
if ((FirstnameText.Text.Trim().Length == 0){
errorMessage("firstname is empty");
}
if (SurnameText.Text.Trim().Length == 0){
errorMessage("surname is empty");
}
有主意嗎?
如果可能的話,您可以像下面這樣重寫代碼
Control errorControl =null;
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
if (ctrl.Name == "MatricNoText")
{
if ((int.Parse(MatricNoText.Text) < 10000 || int.Parse(MatricNoText.Text) > 99999))
{
errorControl = ctrl;
}
}
else if (ctrl.Name == "MatricNoText")
{
if (int.Parse(YearMarkText.Text) < 0 || int.Parse(YearMarkText.Text) > 100)
{
errorControl = ctrl;
}
}
else
{
if (ctrl.Text.Length == 0)
{
errorControl = ctrl;
}
}
}
}
MessageBox.Show("Please check your input." + errorControl.Focus());
我經常使用流利驗證。 WithMessage
方法使您可以指定錯誤消息。 然后,驗證器將為您返回所有錯誤消息的枚舉。 對於您的特定問題,也許還有更好的擬合方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.