Reputation: 93
i have problem with closing saveFileDialog. when i click'cancel' window appears once again. here is my code:
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);
if (saveFileDialog1.ShowDialog()==DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
issaved = true;
SaveFile.WriteLine(richTextBox1.Text);
}
SaveFile.Close();
}
Upvotes: 2
Views: 5032
Reputation: 7757
You're calling saveFileDialog1.ShowDialog()
twice, once to show it and once to get the result. You only need to call it once. Remove the line that says, saveFileDialog1.ShowDialog();
by itself, you're already doing that inside the if
condition.
Edit: you'll also need to move all the FileStream
operations inside of the else block for it to work properly after you remove that line. Here is my edited version:
private void SaveAsItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "untitled";
saveFileDialog1.Filter = "Text (*.txt)|*.txt";
if (saveFileDialog1.ShowDialog()==DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
issaved = true;
SaveFile.WriteLine(richTextBox1.Text);
SaveFile.Close();
}
}
You could also skip the FileStream
altogether an just do a File.WriteAlltext(saveFileDialog1.FileName, richTextBox1.Text)
.
Upvotes: 7