I have a problem with two of my EventHandlers, they work the same, so here is one:
private void Form1_Load(object sender, EventArgs e)
{
webBrowserWebsite.Url = new System.Uri(textBoxURL.Text, System.UriKind.Absolute);
webBrowserWebsite.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserWebsite_DocumentCompleted);
}
void webBrowserWebsite_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\CurrentData.wfd");
sw.Write(webBrowserWebsite.Document.Body.InnerText);
sw.Close();
}
The problem is, that the EventHandler fires multiple times, it doesn’t stop!
Why is it doing this?
Thanks in advance
The code that you have written won’t compile (your
StreamWriterin your EventHandler isn’t assigned to anything) and without more context as to how you are calling this, it is difficult to say for certain.But the most likely reason is you are calling
Form1_Loadmultiple times, but using the samewebBrowserWebsiteobject. Each time the form loads, you are adding a new Event Handler. And since you aren’t showing any code showing where you removing the event handler, I’m guessing it fires once for each time you call Form_Load.Depending on your design, you are better off adding the event handler in the constructor so it is only added once regardless of the number of times you load the form.
Or remove the event handler in the event handler:
Also, since
StreamWriterimplementsIDisposible, you should be putting it inside of ausingblock or at least callingsw.Dispose()at the end of the method