Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i use web browser,i can navigate to site but i can't change elements value like text boxes.

i use this code to fill google text box and click on search button:
C#
private void button1_Click(object sender, EventArgs e)
{
         webBrowser1.Navigate("google.com"); 
         webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_h);
}
private void web_h(object sender, WebBrowserDocumentCompletedEventArgs e)
{
           WebBrowser b = (WebBrowser)sender;
           b.Document.GetElementById("gbqfq").InnerText = "programming"; 
           b.Document.GetElementById("gbqfba").InvokeMember("click");
}

but i face with this error: System.NullReferenceException

can you help me?
Posted
Updated 4-Jul-14 2:34am
v2

1 solution

You are getting the error on line
b.Document.GetElementById("gbqfq").InnerText = "programming";

This is because there is no Element called gbqfq so
b.Document.GetElementById("gbqfq")
is null.
You can't assign values to properties (e.g. .InnerText) of null objects.

You need to check for success find first e.g.
C#
private void web_h(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser b = (WebBrowser)sender;
    HtmlElement  h1 = b.Document.GetElementById("gbqfq");
    if (h1 != null)
        h1.InnerText = "programming";
    h1 = b.Document.GetElementById("gbqfba");
    if (h1 != null)
        h1.InvokeMember("click");
}
 
Share this answer
 
Comments
Abolfazl_d_sh 4-Jul-14 9:41am    
thanks
i try "name" attribute of elements instead their "id" in GetElementById() method and it works right.
but some elements just have "id".
what should i do whit this elements?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900