Benilda Key
Benilda Key

Reputation: 3102

Get HTML CheckBox state in a WebBrowser control

How can I get the state of a HTML CheckBox in a WebBrowser control?

I have the following variable in my class:

private WebBrowser quickStartGuideContentWebBrowser = new WebBrowser();

I also have the following constant in my class:

private const string doNotShowAgainCheckBoxElementId = "do-not-show-again-checkbox";

I also have the following function in my class;

private HtmlElement GetDoNotShowAgainCheckBox()
{
    HtmlDocument document = this.quickStartGuideContentWebBrowser.Document;
    if (document == null)
    {
        Debug.WriteLine("GetDoNotShowAgainCheckBox error: (document == null).");
        return null;
    }
    return document.GetElementById(doNotShowAgainCheckBoxElementId);
}

I am trying to implement a IsDoNotShowAgainCheckBoxChecked method as follows:

private bool IsDoNotShowAgainCheckBoxChecked()
{
    HtmlElement checkboxElement = GetDoNotShowAgainCheckBox();
    if (checkboxElement == null)
    {
        Debug.WriteLine("IsDoNotShowAgainCheckBoxChecked error: (checkboxElement == null).");
        return false;
    }
    // What magical incantation do I put here 
    // to retrieve the checked state of checkboxElement as a bool?
    return false;
}

Upvotes: 2

Views: 325

Answers (1)

Jimi
Jimi

Reputation: 32243

You just need to get the checked Attribute using the HtmlElement.GetAttribute() method.
It will be "True" or "False" (string), based on the state of the CheckBox.

if (quickStartGuideContentWebBrowser.ReadyState != WebBrowserReadyState.Complete) return;

var chkBoxElm = quickStartGuideContentWebBrowser.Document.
    GetElementById(doNotShowAgainCheckBoxElementId);

if (chkBoxElm != null) {
    var state = chkBoxElm.GetAttribute("checked");
    if (state = "True") {
        Console.WriteLine("The CheckBox state is 'checked'");
    }
}

The GetAttribute() method can of course be used to retrieve any other Attribute of an HtmlElement, e.g., its className.

Upvotes: 3

Related Questions