Search code examples
c#winformssave

Why is my save file dialog opening twice when it is run?


I have a small application that needs to save to contents of a rich text box as a text file upon a button click. What I currently have is

//save button logic
private void saveBtn1_Click(object sender, EventArgs e)
{
    //set up new SaveFileDialog
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.Filter = "Text Files (*.txt)|*.txt";
    saveFileDialog1.Title = "Save a text File";

    //prompt the user
    DialogResult result = saveFileDialog1.ShowDialog();

    //if they select save write the contents of the RTB to a text file
    if (result == DialogResult.OK)
    {
        System.IO.File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
    }
}

It seems like a pretty straight forward piece of code, but I can't figure out why the dialog opens twice.


Solution

  • Just expanding Servy's comment into an answer because I suspect his diagnosis is correct. I'm going to give some simple suggestions for diagnosing/finding the problem. Firstly, you can put a break point in the event handler, if you're taken into that event handler twice then that's obviously the problem. The other solution (without even running) is simply to right click on the method name and select "find all references" this will give you list of all the references to the this method within your code. I'm guessing you will find 3; the method itself, the place where you expect to be registering it, and the place you were you don't. Remove the one and your problem will go away.