Joey Morani
Joey Morani

Reputation: 26611

"Specified cast is not valid" error

I'm using this code which is meant to check the text in webBrowser1, although instead I'm getting the error "Specified cast is not valid." for string docText = webBrowser1.Document.Body.InnerText;. Any ideas why? Could it be because I'm accessing the webBrowser from another thread? Thanks.

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    string docText = webBrowser1.Document.Body.InnerText;

    if (docText == "Hello")
    {
        MessageBox.Show("Alerted!");
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

Upvotes: 2

Views: 5189

Answers (4)

Erx_VB.NExT.Coder
Erx_VB.NExT.Coder

Reputation: 4856

The .Body section will return an object null reference exception and .innerHTML will not be recognized as a string if you haven't waited for the page to load, it may be triggering that error you are getting as a result. have you done correct waiting for document to load before all this? check out my answers on how to do proper waiting on webbrowser control if you need help with this.

Upvotes: 0

Enrico Campidoglio
Enrico Campidoglio

Reputation: 60013

The exception may in fact be caused by accessing the WebBrowser.Document property from a thread that isn't the main UI thread. You can verify that by looking for the following lines in the stack trace of the System.InvalidCastException:

at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
at System.Windows.Forms.WebBrowser.get_Document()

If this is the case, try passing the content of the web page to the background thread as an argument instead:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    var docText = (string)e.Argument;
}

private void timer1_Tick(object sender, EventArgs e)
{
    var docText = webBrowser1.Document.Body.InnerText;
    backgroundWorker1.RunWorkerAsync(docText);
}

Upvotes: 5

Steve
Steve

Reputation: 216353

I will try with...

backgroundWorker1.RunWorkerAsync(webBrowser1.Document.Body.InnerText);

this will remove the cast exception

and in DoWork

string docText = e.Argument.ToString();

this will remove the UI thread issue

Upvotes: 2

ebutusov
ebutusov

Reputation: 573

Maybe you should wait for DocumentCompleted event from WebBrowser ctrl before accessing Document.

Upvotes: 0

Related Questions