I am trying to figure out how to click a button on a web page programmatically.
Specifically, I have a WinForm with a WebBrowser control. Once it navigates to the targe
Have you tried fireEvent instead of RaiseEvent?
Just a possible useful extra where the submit button has not been given an Id - as is frequently the case.
private HtmlElement GetInputElement(string name, HtmlDocument doc) {
HtmlElementCollection elems = doc.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("value");
if (!String.IsNullOrEmpty (nameStr) && nameStr.Equals (name))
{
return elem;
}
}
return null;
}
So you can call it like so:
GetInputElement("Login", webBrowser1.Document).InvokeMember("Click");
It'll raise an exception if the submit input with the value 'Login', but you can break it up if you want to conditionally check before invoking the click.
There is an example of how to submit the form using InvokeMember here. http://msdn.microsoft.com/en-us/library/ms171716.aspx
You posted a comment along the lines of not wanting to use a client side script on @Phunchak's answer. I think what you are trying to do is impossible. The only way to interact with the form is via a client side script. The C# code can only control what happens before the page is sent out to the browser.
How does this work? Works for me
HtmlDocument doc = webBrowser1.Document;
doc.All["userIDTextBox"].SetAttribute("Value", "user1");
doc.All["userPasswordTextBox"].SetAttribute("Value", "Password!");
doc.All["logonButton"].InvokeMember("Click");
var btn = document.getElementById(btnName); if (btn) btn.click();