2

I'm fairly new to C#, and I'm trying to get a level from an in-browser game. This is the code I used and it came with an error

"Object reference not set to an instance of an object"

HtmlElementCollection elmnt = webBrowser1.Document
                                         .GetElementById("levelFrontTopArea")
                                         .GetElementsByTagName("value");
levellabel.Text = elmnt[0].InnerText;

Below I will show you the HTML code:

<div class="levelFrontTopArea">
   <a style="text-decoration:none" href="/profile.php">7</a>
</div>
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • While he is getting a `NullReference` exception, its only because he is trying to get a class element that doesnt have an id. The question is actually about how to get a class element. – crthompson Dec 17 '13 at 20:58

2 Answers2

2

If you want to get an element by class you can loop through the div tags.

static IEnumerable<HtmlElement> ElementsByClass(HtmlDocument doc, string className)
{
  foreach (HtmlElement e in doc.All)
    if (e.GetAttribute("className") == className)
      yield return e;
}

You can call it like this:

var elmnt = ElementsByClass(webBrowser1.Document, "levelFrontTopArea");
levellabel.Text = elmnt.FirstOrDefault().InnerText;
crthompson
  • 15,653
  • 6
  • 58
  • 80
  • Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable – Tooproforyahoo Dec 15 '13 at 04:36
  • Oops, just copied your code on that, you can get the first element by using `FirstOrDefault` Because the method returns an IEnumerable, you can use it in a foreach as well. – crthompson Dec 15 '13 at 20:40
0

You're using GetElementByID, but your div has no ID. Try changing your HTML to:

<div ID="levelFrontTopArea" class="levelFrontTopArea">
  <a style="text-decoration:none" href="/profile.php">7</a>
</div>
charlieparker
  • 186
  • 1
  • 8