C# WinForms中发生关闭事件时如何保存数据?
我想要一个消息框,用于询问表单关闭事件中未保存的数据 如果用户选择“是”,则将数据保存在文本文件中并退出应用程序 如果用户选择不退出应用程序而不保存 我尝试了以下代码。但它不会关闭应用程序并使消息框一次又一次出现C# WinForms中发生关闭事件时如何保存数据?,c#,winforms,C#,Winforms,我想要一个消息框,用于询问表单关闭事件中未保存的数据 如果用户选择“是”,则将数据保存在文本文件中并退出应用程序 如果用户选择不退出应用程序而不保存 我尝试了以下代码。但它不会关闭应用程序并使消息框一次又一次出现 public void SaveMyFile() { //// Create a SaveFileDialog to request a path and file name to save to. SaveFileDialog saveFi
public void SaveMyFile()
{
//// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveFile1 = new SaveFileDialog();
//// Initialize the SaveFileDialog to specify the RTF extension for the file.
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = "Info Changed Data (*.txt)|*.txt";
//// Determine if the user selected a file name from the saveFileDialog.
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
//// Save the contents of the RichTextBox into the file.
richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SaveMyFile();
this.Close();
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
删除该行
this.Close();
这是没有必要的。应该是这样的:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SaveMyFile();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNoCancel);
if (dialogResult == DialogResult.Yes) SaveMyFile();
else if (dialogResult == DialogResult.Cancel) e.Cancel = true;
}
或者像这样:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SaveMyFile();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNoCancel);
if (dialogResult == DialogResult.Yes) SaveMyFile();
else if (dialogResult == DialogResult.Cancel) e.Cancel = true;
}
没有循环的“…一次又一次”通常表示程序中存在某种重复
在本例中,您在关闭
事件处理程序中调用Form.Close()
,然后引发关闭
事件,在该事件中调用Form.Close()
,然后。。。我想你明白了
只需删除对
Close()
的调用,您就不需要它们了。如果Closing
被触发,那么您的表单将被关闭,除非您将FormClosingEventArgs
参数中的Cancel
属性设置为true
,在选择“是”并保存文件时,它会再次弹出询问相同问题的消息。@swagger即使您通过删除此参数修改了代码。Close()声明?我现在已经试过了,对我来说,它像这样工作得很好。