Voided
Voided

Reputation: 3

Why does HtmlElementEventArgs.ToElement return null?

I am trying to detect a certain element when it's clicked in a web browser.

Here's my code:

try
{
   htmlElement.MouseDown -= new 
   HtmlElementEventHandler(webBrowser1_MouseDown);
}
catch (Exception)
{
}
htmlElement.MouseDown += new HtmlElementEventHandler(webBrowser1_MouseDown);

This code is called on webBrowser1.GotFocus & webBrowser1.LostFocus.

Here is the code for MouseDown.

    public void webBrowser1_MouseDown(object sender, HtmlElementEventArgs e)
    {
        HtmlElement element = e.ToElement;
        Console.WriteLine(element);
    }

For some reason whenever I click on the item. element is equal to null?

but if I do

try
{
    Console.WriteLine(htmlElement.Name); // works
    htmlElement.MouseDown -= new 
    HtmlElementEventHandler(webBrowser1_MouseDown);
}
catch (Exception)
{
}
htmlElement.MouseDown += new HtmlElementEventHandler(webBrowser1_MouseDown);

Upvotes: 0

Views: 152

Answers (1)

Gaurang Dave
Gaurang Dave

Reputation: 4046

Two things I noticed in code you shared, you can fix them very easily.

  1. htmlElement - you declared this on Page and registered MouseDown event with it. You can access it anywhere in the page. There is no need of another HtmlElement object in the event.

  2. What you receive in e is HtmlElementEventArgs not any element. I would suggest you to use sender object to get the element.

Upvotes: 1

Related Questions