我有一个用<class>.ShowDialog()
显示的对话框.它有一个确定按钮和一个取消按钮;OK按钮还有一个事件处理程序.
我想在事件处理程序中进行一些输入验证,如果失败,用消息框通知用户,并阻止对话框关闭.我不知道如何做最后一部分(防止关闭).
我有一个用<class>.ShowDialog()
显示的对话框.它有一个确定按钮和一个取消按钮;OK按钮还有一个事件处理程序.
我想在事件处理程序中进行一些输入验证,如果失败,用消息框通知用户,并阻止对话框关闭.我不知道如何做最后一部分(防止关闭).
Given that you've specified you want a pop error dialog,一种方法是将验证转移到OnClosing
事件处理程序中.在本例中,如果用户对对话框中的问题回答"是",则表单关闭被中止.
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
通过设置e.Cancel = true
,您将防止窗体关闭.
However, it would be a better design/user experience to display the validation errors inline(通过以某种方式突出显示有问题的字段、显示工具提示等)and prevent the user from selecting the OK button in the first place.