0

I'm trying to use this snippet to test of an element has a specific text.

HtmlDocument element = webBrowser2.Document;

if (element.GetElementById("gbqfsa").InnerText == "Google Search")
{
     HasSucceeded = 1;
}
return HasSucceeded;

However the first line throws the exception "Specified cast is not valid." What am I doing wrong?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
sir_thursday
  • 5,270
  • 12
  • 64
  • 118

2 Answers2

2

Is it possible that you are using the wrong HtmlDocument class? WebBrowser.Document is of the type:

System.Windows.Forms.HtmlDocument

But I noticed that there is also another possible namespace:

System.Windows.Browser.HtmlDocument

I would check to make sure the namespace you included was System.Windows.Forms.HtmlDocument

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • if I try to include `System.Windows.Forms.HtmlDocument` in addition to the `System.Windows.Form` namespace I'm already using, I get an error. "A using namespace directive can only be applied to namespaces; 'System.Windows.Forms.HtmlDocument' is a type not a namespace." – sir_thursday Jul 24 '13 at 16:09
0

I encounter this problem when return HtmlDocument as property from my custom user control. (Which embedded WebBrowser control)

Cause of error because access document from other thread.

/// <summary>
/// Error version '
/// </summary>
public HtmlDocument Document
{
    get
    {
        // Throw error 'Specified cast is not valid'
        return this.webBrowserMain.Document; 
    }
}

But I don't known why error is not 'CrossThread Operation access ...' but next code solved my problem

/// <summary>
/// Fixed version
/// </summary>
delegate HtmlDocument DlgGetDocumentFunc();
public HtmlDocument GetDocument()
{
    if(InvokeRequired)
    {
        return (HtmlDocument)this.webBrowserMain.Invoke(new DlgGetDocumentFunc(GetDocument), new object[] { });
    }
    else
    {
        return this.webBrowserMain.Document;
    }
}
Sum Settavut
  • 1
  • 1
  • 1