Error extracting data with WebBrowser by ID

1

In an application WinForms , my code extracts without problems the data of a web with this code:

Elemento3.Text = WebBrowser1.Document.GetElementById("Elemento1").InnerText
Elemento3.Text = WebBrowser1.Document.GetElementById("Elemento2").InnerText
Elemento3.Text = WebBrowser1.Document.GetElementById("Elemento3").InnerText
Elemento3.Text = WebBrowser1.Document.GetElementById("Elemento4").InnerText

The page where I extract it sometimes has up to 4 IDs that I capture, however, the web sometimes only shows 3 IDs, so when searching my application the "Element4", it does not find it and it throws me this error:

How can I do so that when I do not find the IDs I simply ignore it and leave the textbox where it extracts the data empty?

    
asked by Abaol 23.07.2017 в 00:15
source

1 answer

2

GetElementByID returns null when the element is not present:

  

Returns the first object with the same ID attribute as the specified   value, or null if the id can not be found.

GetElementByID - MSDN

The problem is that you try to access the InnerText of an element that is null , that's why you get NullReferenceException .

The simplest (and one of the suggestions that the IDE provides you) would be to assign the InnerText only when the result of obtaining Elemento4 is not null.

HtmlElement elem4 = WebBrowser1.Document.GetElementById("Elemento4")
 If (elem4 IsNot Nothing) Then         
  Elemento3.Text = elem4.InnerText
 End If
    
answered by 23.07.2017 в 03:37