在C# WinForms中處理數據驗證,可以通過以下幾種方法:
private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox textBox = sender as TextBox;
if (string.IsNullOrWhiteSpace(textBox.Text))
{
e.Cancel = true;
MessageBox.Show("輸入不能為空");
}
}
private bool ValidateInput(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
// 添加更多的自定義驗證邏輯
return true;
}
private bool IsValidEmail(string email)
{
string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
return Regex.IsMatch(email, pattern);
}
無論使用哪種方法,都需要在用戶提交表單時觸發驗證。你可以在Form的Click事件或Submit按鈕的Click事件中調用驗證方法,并在驗證失敗時阻止表單提交。例如:
private void form_Click(object sender, EventArgs e)
{
if (!ValidateForm())
{
MessageBox.Show("驗證失敗,請檢查輸入");
return;
}
// 提交表單
}
private bool ValidateForm()
{
// 調用所有驗證方法并返回結果
return ValidateTextBox() && ValidateEmail();
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。