Uncheck a checkbox in webpage through WebBrowser control
Solution 1
You can use:
webBrowser.Document.InvokeScript
see:
This way you can call JS function that will do what you want to the page.
Another way is to use mshtml API, like this:
( ( HTMLInputElement )this.webBrowser1.Document.GetElementById( "test" ).DomElement ).@checked = false;
Solution 2
You can use the InvokeMember Method of a HTML Element to invoke a DOM Event. In our case "click". If you have a WebBrowser Control than all you have to do is find the element and Invoke the Method.
For Each ele As HtmlElement In Me.WebBrowser1.Document.All
If ele.Name = "accept" Then
ele.InvokeMember("click")
End If
Next
In my example 'accept' was the name of the checkbox element. You can use the SetAttribute() for some other controls but the best way to emulate a click is to find what the checkbox state is by using GetAttribute() and click if the checkbox is set to false. Hope it helps.
user
Updated on June 05, 2022Comments
-
user almost 2 years
Is there a way to uncheck/check a checkbox within a webpage that is loaded within a webbrowser control? Thank you.
Update: (This is what I originally tried with no luck)
HtmlDocument rememberme = this.webBrowser1.Document; rememberme.GetElementById("remBox").SetAttribute("checked", "false");
-
RegisteredUser over 14 yearsWhat does that have to do with the webbrowser control?
-
Sheng Jiang 蒋晟 over 14 yearsIt would be more complicated if you skip .Net's wrapper classes and call IE API directly.
-
user over 14 yearsWhat would be a proper way to use JavaScript to uncheck a single checkbox?
-
RegisteredUser over 14 yearsMy point is that once you've got the document in the webbrowser control you can manipulate the dom objects directly, without resorting to javascript.
-
Majkel over 14 yearsIt depends - if you know checkbox's ID, then just use
document.getElementById( 'yourid' ).checked = false;
But if it is dynamic (like in ASP.NET in control) than you would have to use another way - locate it by class name, traverse DOM tree or something. -
Majkel over 14 yearsIt should be
input.@checked = false;
. And using JS you don't have to reference mshtml and you can do this in one line -this.webBrowser1.Document.InvokeScript( "uncheck" );
. -
Majkel over 14 yearsWell, one line in C# + one in JS.
-
RegisteredUser over 14 yearsWell I could condense it down to one line of C# if I really wanted to. ;) I suspect actually adding the script to the page and using it would end up being more.
-
Majkel over 14 yearsSolution with mshtml in my answer actually is one line ;) And JS approach to be one line would require access to the page source - otherwise it would be necessary to use mshtml API to insert your script.