-1

I have this code here in my program:

foreach (HtmlElement chat in wb.Document.GetElementsByTagName("input"))
{
    if (chat != null)
    {
        if (chat.InnerText.Equals("Chat"))
        {
            chat.InvokeMember("Click");
            loggedIn = true;
            break;
        }
    }
}

Once it gets to the if(chat.InnerText.Equals("Chat")) it throws a NullReferenceException Error as shown in the ScreenShot below:

Error Code

Does anyone know why it is giving me that? I even put the if (chat != null) code in there, and it still throws it.

This is the website code:

<div class="ContentTab">
    Chat
</div>
Jack Nelson
  • 83
  • 1
  • 6

4 Answers4

2

Chat.InnerText is null, even though Chat isn't. Try this:

foreach (HtmlElement chat in wb.Document.GetElementsByTagName("input"))
{
        if (chat != null && chat.InnerText != null && chat.InnerText.Equals("Chat"))
        {
            chat.InvokeMember("Click");
            loggedIn = true;
            break;
        }
}
Michael B
  • 581
  • 1
  • 5
  • 17
2

The property InnerText of chat variable is null

nraina
  • 324
  • 2
  • 20
1

try

    if (chat.InnerText == "Chat")
    {
        chat.InvokeMember("Click");
        loggedIn = true;
        break;
    }

I believe that .Equals checks object similarity, and operator == checks reference equality.

JKennedy
  • 18,150
  • 17
  • 114
  • 198
1

you can try checking the object itself its empty try this

foreach (HtmlElement chat in wb.Document.GetElementsByTagName("input"))
{
    if (chat != null && (!chat.isEmpty())&& chat!="")
    {
        if (chat.InnerText.Equals("Chat"))
        {
            chat.InvokeMember("Click");
            loggedIn = true;
            break;
        }
    }
}