0

I am trying to automate fill the textbox of a website in c# and i used:

 private void button1_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.WebBrowser webBrowser = new WebBrowser();
        HtmlDocument document = null;
        document=webBrowser.Document;
        System.Diagnostics.Process.Start("http://www.google.co.in");

        document.GetElementById("lst-ib").SetAttribute("value", "ss");
    }

The webpage is opening but the text box is not filled with the specified value. I have also tried innertext instead of setAttribute. I am using windows forms.

user3201928
  • 378
  • 1
  • 6
  • 23

2 Answers2

2

You are expecting that your webBrowser will load the page at specified address, but actually your code will start default browser (pointing at "http://www.google.co.in"), while webBrowser.Document will remain null.

try to replace the Process.Start with

webBrowser.Navigate(yourUrl);
Gian Paolo
  • 4,161
  • 4
  • 16
  • 34
  • Still having the same error but for previous Process.Start the program opened the webpage but with navigate the webpage is not opened and it goes straight for the error. – user3201928 Nov 30 '15 at 10:04
0

Eliminate the Process.Start() statement (as suggested by Gian Paolo) because it starts a WebBrowser as an external process.

The problem with your code is that you want to manipulate the value of your element too fast. Wait for the website to be loaded completely:

private void button1_Click(object sender, EventArgs e)
{
   System.Windows.Forms.WebBrowser webBrowser = new WebBrowser();

   webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);

   webBrowser.Navigate("http://www.google.co.in");
}


private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
   webBrowser.document.GetElementById("lst-ib").SetAttribute("value", "ss");   
}

Please note that using a instance of a WebBrowser is not often the best solution for a problem. It uses a lot of RAM and has some overhead you could avoid.

Stefan Wanitzek
  • 2,059
  • 1
  • 15
  • 29