How can I click a checkbox using HtmlAgilityPack

c# html-agility-pack

Question

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(webBrowser.DocumentText);
HtmlNode n = doc.DocumentNode.SelectSingleNode("//*[contains(@class, 'checkbox')]");

<table class="list" cellspacing="0">
<tbody>
  <tr>
    <th width="45" class="checkAll"><input title="Select all" class="checkbox" type="checkbox" value=""></th>

    <th><span>Account</span></th>

    <th><span>Target system</span></th>
  </tr>

  <tr class="checkable">
    <td><input name="item1" class="checkbox" type="checkbox"></td>

    <td><span>sometext1</span></td>

    <td><span>system1</span></td>
  </tr>

  <tr class="checkable odd">
    <td><input name="item2" class="checkbox" type="checkbox"></td>

    <td><span>sometext2</span></td>

    <td><span>stystem2</span></td>
  </tr>

  <tr class="foot">
    <td colspan="4"><input name="SUBMIT" class="submit" type="submit" value="Unlock"></td>
  </tr>
  </tbody>
  </table>

I am trying to click the first checkbox that says "Select all" so that all the other checkboxes below are selected.

I think my C# code is suppose to load the HtmlNode but I can't figure out how to click it.

Any suggestions would be helpful.

Accepted Answer

I don't think you can use HtmlAgilityPack to check a checkbox. Yes you can change the dom in your doc object so that the checkbox is checked and set the DocumentText of the webbrowser control as your htmldocument but I doubt that's what you want to do.

If you have the page open in the webBrowser, you can use something like this:

webBrowser1.Document.GetElementsByTagName("input")[0].InvokeMember("click");

But this will only select the first checkbox.

If you want all checkboxes to be selected, you can either iterate the above code for all input elements or use server side javascript to check all checkboxes when the first checkbox is checked.

Again, I can help you further if you explain what you want a little bit more clearly.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why