我是C#的新手,并且对话框有点问题。我在一个按钮上有一个事件监听器,用于在我的文本编辑器中打开现有文件。现有的文件功能打开文件等没有任何问题。
问题:我需要向用户显示一条消息,指出在弹出OpenFileDialog之前文本框中的任何内容都将丢失。单击“确定”后,将显示OpenFileDialog,单击“取消”将返回当前文档。
我可以让他们中的任何一个独立工作,但不能在一起工作。由于if中的if不可行,我不确定如何处理这个:s
我的代码:
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files|*.txt";
if (open.ShowDialog() == DialogResult.OK)
{
rtb.LoadFile(open.FileName,
RichTextBoxStreamType.PlainText);
}
}
需要添加什么:
DialogResult confirm =
MessageBox.Show("Your changes will not be saved!", "Are you sure?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (confirm == DialogResult.OK)
{
}
else if(confirm == DialogResult.Cancel)
{
}
我真的觉得我有一些非常简单的解决方案。不幸的是我在这方面找不到任何东西。自从我上次编码以来已经有一段时间了。
答案 0 :(得分:1)
DialogResult confirm =
MessageBox.Show("Your changes will not be saved!", "Are you sure?", ...)
if (confirm == DialogResult.OK)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files|*.txt";
if (open.ShowDialog() == DialogResult.OK)
{
rtb.LoadFile(open.FileName,
RichTextBoxStreamType.PlainText);
}
}
else if(confirm == DialogResult.Cancel)
{
}
请注意,在这种特殊情况下,else if
是超级的,可以安全地删除。