My problem is simple yet i cannot figure out why it’s not working inside of if/loop. Here are some examples:
Working one:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementById("login").SetAttribute("value", "something");
webBrowser1.Document.GetElementById("password").SetAttribute("value", "something");
}
Non working one:
if (webBrowser1.IsBusy == false)
{
webBrowser1.Document.GetElementById("login").SetAttribute("value", "something");
webBrowser1.Document.GetElementById("password").SetAttribute("value", "something");
}
No matter what the “if” statement is, it’s not working. Also tried with “for”, also tried to get it out of the loop of “for”, i still get this error: “Object reference not set to an instance of an object.”
I’m taking a guess here because of the limited information.
I think you are trying to modify the page right after setting the
Urlproperty. The webpage will not yet be loaded then so the controls you are getting are not available yet.Try adding the code to the
DocumentCompletedevent of theWebBrowser. This event will be triggered right after the document is fully loaded and the elements will be available then.more: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentcompleted.aspx
Update
Your assumption about
IsBusyis not completely correct. It starts outfalsewhen nothing is loaded. settings theUrlproperty will not immediately set it totrue.For an alternative you requested you could use the
ReadyStateproperty that will have the value ofWebBrowserReadyState.Completewhen loading is done. you could use the following example. Although i personally don’t like it as there is the risk of endless loop when the page can’t load for some reason. I would advise to use theDocumentCompletedif possible and i modified that example to correctly handle non-login pages as well.