2
private void button1_Click(object sender, EventArgs e)
{
    string url = urlTextBox.Text;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    richTextBox1.Text = sr.ReadToEnd();
    webBrowser1.DocumentText = richTextBox1.Text;
    HtmlElement htmlElement = webBrowser1.Document.GetElementById("name");
    string data = htmlElement.InnerText;
    label1.Text = data;
    sr.Close();
}

I want to read some text inside id element of php file, but it's had problem a little at this line

string data = htmlElement.InnerText;

and I get some warning from Visual Studio 2010

NullReferenceExpection was unhandled
Object reference not set to an instance of an object.

Could anyone please help me? Thank you :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mekhy
  • 21
  • 3
  • 1
    The error you are getting indicates there is no element with the ID `name`. – Oded Jun 24 '12 at 17:26
  • 2
    See @Smi's answer and better use [Html Agility Pack](http://htmlagilitypack.codeplex.com/) instead of WebBrowser control. – L.B Jun 24 '12 at 17:40

2 Answers2

2

I believe the problem here could be that the WebBrowser control loads the document asynchronously. So when you're trying to access webBrowser1.Document immediately after, things go wrong.

DocumentText property from MSDN:

If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new content. You can retrieve the new value in a DocumentCompleted event handler. Alternatively, you can block the thread until the document is loaded by calling the Thread.Sleep method in a loop until the DocumentText property returns the value that you originally set it to.

See also DocumentCompleted event.

Smi
  • 13,850
  • 9
  • 56
  • 64
0

Most likely the method cannot find an element with ID "name" and thus the variable htmlElement is null. Check if the website you try to fetch has an element with that ID.

KBoek
  • 5,794
  • 5
  • 32
  • 49