-2

I'm working with window forms on c# I'm trying to open a file using openfile dialog when I browse to my file and open it the open file dialog keeps on showing many times .

That's my code for opening a file :

private void OpenBtn_Click(object sender, EventArgs e)
{
    // Create OpenFileDialog 
    OpenFileDialog dlg = new OpenFileDialog();

    // Set filter for file extension and default file extension 
     dlg.DefaultExt = ".xml";
    dlg.Filter = "XML Files (*.xml)|*.xml";

    // Display OpenFileDialog by calling ShowDialog method 
    DialogResult result = dlg.ShowDialog();
    if (result == DialogResult.OK)
    {
        pathtext.Text = dlg.FileName;
        sourceName = dlg.FileName;
    }
    //  destFile = resultFile.Name;
    if (pathtext.Text != null)
    {
        createBtn.Enabled = true; 
    }
}

and this event handler of the method in the form load

OpenBtn.Click += new EventHandler(this.OpenBtn_Click);

I can't see where did I miss the thing.

Code4Living
  • 35
  • 1
  • 8

1 Answers1

0

The only way I can reproduce your bug is when I double click the button in the designer so that it creates an automatic event handler which you can see in the event properties: enter image description here

If I then in addition to that add inside the code a manual registration of the event Click for example in the Load event:

private void Form1_Load(object sender, EventArgs e)
{
   button2.Click += new EventHandler(this.OpenBtn_Click);
}

Then I will get the behaviour that the dialog pops up twice. If I do it one more time:

private void Form1_Load(object sender, EventArgs e)
{
   button2.Click += new EventHandler(this.OpenBtn_Click);
    button2.Click += new EventHandler(this.OpenBtn_Click);
}

It will pop up 3 times! It is very likely that you register this event in a loop. So when the first one is executed all others just follow up. Remove the manual registering line and put the event handler name simply into the event properties.

EDIT: The main problem is the operator += it adds the delegates to an internal list as described in this answer.

Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • Thank you so much @MongZhu your answer solved the problem (y) – Code4Living May 17 '17 at 16:06
  • @asma The main problem is the operator `+=` it adds the delegates to an internal list as described in [this answer](http://stackoverflow.com/a/3356424/5174469). – Mong Zhu May 18 '17 at 08:23