RobinВricks
RobinВricks

Reputation: 93

Wait until page loads in webbrowser C#

I have a program that testing the web page - clicking on the web elements. I'm using the C# WebBrowswer control and I have a problem before inserting the text in the text field, I want to wait for the page to load. for wait for the page to load, I'm using :

    while (true)
    {
    System.Windows.Forms.Application.DoEvents();
        foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
        {
            if (el.GetAttribute("title") == "Custom") != null)
            {
                break;
            }
        }
    }

but I get an error in the line: var elmC = web_Browser.Document.GetElementsByTagName("input"); "unreachable code detected"

        public void GetStatus(string innerText)
        {
            try
            {
                while (true)
                {
                    System.Windows.Forms.Application.DoEvents();
                    foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
                    {
                        if (el.GetAttribute("title") == "Custom") != null)
                        {
                           break;
                        }
                    }
                }


                var elmC = web_Browser.Document.GetElementsByTagName("input");
                foreach (HtmlElement elm in elmC)
                {
                    if (elm.Id == "num")
                    {
                        elm.InnerText = String.Empty;
                        Wait(1);
                        elm.InnerText = innerText;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error " + ex.Message);
            }
        }

Upvotes: 0

Views: 61

Answers (1)

Sam
Sam

Reputation: 1358

Your break; statement is only going to break out of the foreach loop, not the while(true) loop, so that loop will run forever, any code after is unreachable...

Maybe try something like :

var run = true;

 while (run)
                {
                    System.Windows.Forms.Application.DoEvents();
                    foreach (HtmlElement el in web_Browser.Document.GetElementsByTagName("р"))
                    {
                        if (el.GetAttribute("title") == "Custom") != null)
                        {
                           run = false;
                        }
                    }
                }

But usually any code that reads " while() { // check async operation } " is generally bad ... Consider using an event or Thread.sleep() perhaps

Upvotes: 1

Related Questions