Search code examples
c#oopmessagebox

C# message box appears twice


I am trying to do a simple World of Warcraft profile picture "extractor". Here is my code:

private void pictureBox1_Click(object sender, EventArgs e)
{
    if (textBox4.Text != "")
    {
        webBrowser1.ScriptErrorsSuppressed = true;
        webBrowser1.Navigate("https://worldofwarcraft.com/en-gb/search?q=" + textBox4.Text);
        webBrowser1.DocumentCompleted += GetImg;
    }
}
private void GetImg(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    string result = "";
    foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
        if (el.GetAttribute("className") == "Avatar-image")
        {
            result = (el.OuterHtml).Substring(el.OuterHtml.IndexOf("https"));
            result = result.Substring(0, result.IndexOf(")"));
            pictureBox1.ImageLocation = result;
            DialogResult YESNO = MessageBox.Show("Is this your character?", "Select your char", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (YESNO == DialogResult.Yes)
            {
                break;
            }
        }
    }
}

The problem is that I click the image once and if the character is the right one I click "Yes" and everything is good. However if I click the image a second time the message box will pop up, then I chose my answer BUT the message box pops up again. If I am to click the image a third time, the message box will appear 3 times... Any ideas?


Solution

  • You are subscribing to the event an additional time each time you click it on this line:

    webBrowser1.DocumentCompleted += GetImg;