hagai
hagai

Reputation: 464

Wait until page loads in webbrowser control

I'm using the C# WebBrowswer control and I have a problem that when a button like "Next" is pressed when the page is not loaded yet the program tries to proceed but instead gives me a null error.

Is there is a function to make the program wait until the page has completed loading?

I tried to put a while loop in the program that checks the title of the html page but then the program freezes. Something like will freeze the program:

    while(!webbrowser1.Document.Title.ToString().Equals("NextPageTitle"))
   {
   }
   ::NextCommands::

It Doesnt work, i tried that and the button "fblqf" is not clicked. but its not returns null error..

public void button1_Click(object sender, EventArgs e)
{



    webBrowser1.Document.GetElementById("q").SetAttribute("value", "חחח");
    webBrowser1.Document.GetElementById("btnK").InvokeMember("Click");
    webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;


}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // do the work you need to do now that that page has completed loading
    webBrowser1.Document.GetElementById("fblqf").InvokeMember("Click");
}

Solution:

public void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Document.GetElementById("q").SetAttribute("value", "חחח");
    webBrowser1.Document.GetElementById("btnK").InvokeMember("Click");
    int x=0;
    while (x==0)
   {
       System.Windows.Forms.Application.DoEvents();
        if(webBrowser1.Document.GetElementById("pnnext") != null)
        break;
   }

    webBrowser1.Document.GetElementById("pnnext").InvokeMember("Click");
    webBrowser1.Document.GetElementById("q").Focus();
}

Upvotes: 3

Views: 11819

Answers (2)

hagai
hagai

Reputation: 464

I Found an easy Solution!!!

public void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Document.GetElementById("q").SetAttribute("value", "חחח");
    webBrowser1.Document.GetElementById("btnK").InvokeMember("Click");

    while (true)
   {
       System.Windows.Forms.Application.DoEvents();
        if(webBrowser1.Document.GetElementById("pnnext") != null)
        break;
   }

    webBrowser1.Document.GetElementById("pnnext").InvokeMember("Click");
    webBrowser1.Document.GetElementById("q").Focus();
}

Upvotes: 1

Brad Rem
Brad Rem

Reputation: 6026

You need to hook the WebBrowswer.DocumentCompleted event:

Perhaps in your constructor or your OnLoad:

webBrowser1.Document.GetElementById("q").SetAttribute("value", "חחח"); 
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted; 
webBrowser1.Document.GetElementById("btnK").InvokeMember("Click"); 

Then you event looks like this:

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // do the work you need to do now that that page has completed loading
}

Upvotes: 7

Related Questions