Reputation: 3611
this is inside my sample.html
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="testingID">hello</div>
</body>
</html>
and i have this code in c# that i want to prompt is the world "hello" inside the div element with the id testingID
private void btnGetData_Click(object sender, EventArgs e)
{
string url = string.Format("{0}/sample.html", Environment.CurrentDirectory);
WebBrowser webb = new WebBrowser();
webb.Navigate(url);
var doc = webb.Document;
HtmlElement elem = doc.GetElementById("testingID");
MessageBox.Show(elem.InnerText);
}
but i get Object reference not set to an instance of an object. on MessageBox.Show(elem.InnerText);
a little help here..
Upvotes: 1
Views: 2195
Reputation: 5136
I'm assuming that elem is null because an element with an ID of 'testingID' is not being found in the document. Try stepping through with a debugger and verifying that elem is not null. Alternatively, try something like the following:
if (elem != null)
{
MessageBox.Show(elem.InnerText);
}
else
{
MessageBox.Show('No element found!');
}
Upvotes: 1
Reputation: 9124
Probably, you are trying to access the element, but the document is not loaded at the moment. Move doc.GetElementById("testingID");
in WebBrowser.DocumentCompleted event and it should work.
Upvotes: 5