Arj*_*jan 139
您可以通过设置窗体的取消收DialogResult至DialogResult.None.
button1是AcceptButton的示例:
private void button1_Click(object sender, EventArgs e) {
if (!validate())
this.DialogResult = DialogResult.None;
}
Run Code Online (Sandbox Code Playgroud)
当用户点击按钮1和验证方法返回false,形式不会被关闭.
Chr*_*isF 45
鉴于您已指定需要弹出错误对话框,一种方法是将验证移动到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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过设置,e.Cancel = true您将阻止表单关闭.
但是,以内联方式显示验证错误(通过以某种方式突出显示有问题的字段,显示工具提示等)并防止用户首先选择"确定"按钮将是更好的设计/用户体验.
Han*_*ant 16
不要为此使用FormClosing事件,您将希望允许用户通过取消或单击X来关闭对话框.只需实现OK按钮的Click事件处理程序,并且在您满意之前不要关闭:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
Run Code Online (Sandbox Code Playgroud)
"ValidateControls"是您的验证逻辑.如果出现问题,则返回false.
| 归档时间: |
|
| 查看次数: |
79630 次 |
| 最近记录: |