How to Click a Button in a Webbrowser Control

How do you click a button in a webbrowser control?


If you have an ID use this:


If you have TagName use this


In Web Browser DocumentCompleted event

HtmlElement textElement = webBrowser1.Document.All.GetElementsByName("q")[0];
textElement.SetAttribute("value", "your text to search");
HtmlElement btnElement = webBrowser1.Document.All.GetElementsByName("btnG")[0];

If you have name Class use this:

HtmlElementCollection classButton = webBrowser1.Document.All;
foreach (HtmlElement element in classButton)
if (element.GetAttribute("className") == "button")

For adding text in a TextBox to search, use this:

 webBrowser1.Document.GetElementById("gs_tti0").InnerText = "hello world";

Click on a button in a WebBrowser control

Try this :

"get collection of all div in the webpage"
For Each divSect As HtmlElement In WebBrowser1.Document.GetElementsByTagName("div")

"get the div which has the tag of Two Cell"
If divSect.OuterHtml.Contains("Two Cell") then

"get the button inside the div which has the tag of Two Cell"
For Each elem as HtmlElement In divSect.children
If elem.GetAttribute("className") = "button" Then
End if
End if

I hope those code could solve your problem.

C# reach click button in webbrowser?

I write an example for you(how get event clicked button):

private void Form1_Load(object sender, EventArgs e)
//Or navigate to your url
webBrowser1.DocumentText = "<html><body><button id=\"btn1\" type=\"button\">Click Me!</button><button id=\"btn2\" type=\"button\">Click Me!</button></body></html>";

Call Click event:(when page loaded)

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);

Get Active Element When User click on document

 void Document_Click(object sender, HtmlElementEventArgs e)
//Check Element is Button
if (webBrowser1.Document.ActiveElement.TagName == "BUTTON")
if (webBrowser1.Document.ActiveElement.Id== "your button id")
//Do someting

Click button after webBrowser1_DocumentCompleted event

After finding that the addition of a MessageBox allows the webBrowser1.Document to complete, and using webBrowser1.ReadyState event within the webBrowser_DocumentCompleted event, all I needed to do, was to find a way to programmatically close the MessageBox.

Further searching on StackOverFlow revealed the following solution on the site below.

Close a MessageBox after several seconds

Implementing the AutoClosingMessageBox, and setting a time interval, closed the MessageBox and allowed my button click, i.e. btnMyUrl.PerformClick(); to successfully parse the OuterHtml and now the code works properly.

Hopefully, if someone else discovers that placing a MessageBox within the webBrowser_DocumentCompleted event allows the document to complete; the aforementioned AutoClosingMessageBox will assist them as well.

Related Topics

Leave a reply