Jon*_*han 1 c# forms validation savechanges winforms
我试图创建一个event handler这样的用户,当用户选择close(x)按钮时,它会提示用户保存任何未保存的更改.这是我的C#代码:
private void CloseFileOperation()
{
// If the Spreadsheet has been changed since the user opened it and
// the user has requested to Close the window, then prompt him to Save
// the unsaved changes.
if (SpreadSheet.Changed)
{
DialogResult UserChoice = MessageBox.Show("Would you like to save your changes?", "Spreadsheet Utility",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
switch (UserChoice)
{
case DialogResult.Yes:
SaveFileOperation();
this.Close();
break;
case DialogResult.No:
this.Close();
break;
case DialogResult.Cancel:
return;
}
}
// If the Spreadsheet hasn't been changed since the user opened it, then
// simply Close the window.
else
this.Close();
}
Run Code Online (Sandbox Code Playgroud)
我创建MainFram_FormClosing了用户选择close(x)按钮时触发的事件处理程序.
private void MainFrame_FormClosing(object sender, FormClosingEventArgs e)
{
// Close the Spreadsheet.
CloseFileOperation();
}
Run Code Online (Sandbox Code Playgroud)
每当我选择关闭按钮时,应用程序崩溃了..我已阅读this帖子中的回复.我想我违反了Windows 7 Program Requirements.我想我不明白为什么这个功能不能轻易完成.
这方面最好的方法是什么?
如果使用事件处理程序本身而不是单独的例程,则可以访问FormClosingEventArgs,这将允许您在必要时取消关闭.您也正在使用this.Close();,它只是重新启动事件,而不是返回并让事件结束.当我使用此代码集作为事件处理程序时,它按预期在Win7上工作:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if(SpreadSheet.Changed)
{
switch(MessageBox.Show("Would you like to save your changes?", "Spreadsheet Utility",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
{
case DialogResult.Yes:
SaveFileOperation();
return;
case DialogResult.No:
return;
case DialogResult.Cancel:
e.Cancel = true;
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2788 次 |
| 最近记录: |