I am trying to write notepad, how do I know if user clicked ‘Cancel’? My code doesn’t work:
private void SaveAsItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "untitled";
saveFileDialog1.Filter = "Text (*.txt)|*.txt";
saveFileDialog1.ShowDialog();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
SaveFile.WriteLine(richTextBox1.Text);
SaveFile.Close();
if (DialogResult == DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
issaved = true;
}
}
You’re checking the
DialogResultproperty for your main form, but it’s the child form that you want to check. So…Also, you should wrap your
StreamWriterin ausingblock as I have done above. Your code will fail to close the file if an exception occurs. Ausingblock is syntactic sugar for atry/finallyblock which callsDispose()(which in turn callsClose()) in thefinallyportion.