C# System.InvalidCastException

14,198

The following solves your cross thread issue.

public delegate string GetStringHandler();
public string GetDocumentText()
{
    if (InvokeRequired)
        return Invoke(new GetStringHandler(GetDocumentText)) as string;
    else
        return webBrowser.DocumentText;
}

if (regAddId.IsMatch(GetDocumentText()))
{
}
Share:
14,198
Hooch
Author by

Hooch

Updated on June 13, 2022

Comments

  • Hooch
    Hooch about 2 years

    Why I'm getting this error?

    enter image description here

    System.InvalidCastException was unhandled by user code
      Message=Specified cast is not valid.
      Source=System.Windows.Forms
      StackTrace:
           at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
           at System.Windows.Forms.WebBrowser.get_Document()
           at System.Windows.Forms.WebBrowser.get_DocumentStream()
           at System.Windows.Forms.WebBrowser.get_DocumentText()
           at SiteBot.MainWindow.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\Documents\Visual Studio 2010\Projects\SiteBot\MainWindow.cs:line 35
           at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
           at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
      InnerException: