Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Service Webbrowser object invalid cast exception error

Tags:

browser

c#

.net

I'm having a bit of trouble with a Windows Service webbrowser object. It's attempting to load in values of username and password to a site but keeps failing and throwing the following error:

System.InvalidCastException: Specified cast is not valid. at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation() at System.Windows.Forms.WebBrowser.get_Document() at MyWindowsService.MyDataProcessor.login()

The code that I'm using to make this call is:

MyWebBrowser.Document.All["Login"].SetAttribute("Value", username);
            MyWebBrowser.Document.All["Password"].SetAttribute("Value", password);
            MyWebBrowser.Document.All["submit"].InvokeMember("Click");

Any ideas as to why it keeps failing? Thanks in advance for the help.

like image 225
Sam Youtsey Avatar asked Nov 05 '22 16:11

Sam Youtsey


1 Answers

I'm not sure if this solves the problem, but you can check InvokeRequired property on the current object, or WebBrowser.InvokeRequired, and use something like MethodInvoker to call your function or a helper function to access WebBrowser.Document.

http://www.megasolutions.net/cSharp/(WebBrowser_Document-==-null)-throws-InvalidCastException-43126.aspx

like image 85
Axl Avatar answered Nov 14 '22 22:11

Axl