Hi i am trying to click a button using c# but i keep getting a casting error
Unable to cast COM object of type 'mshtml.HTMLInputElementClass' to class type 'mshtml.HTMLButtonElementClass'. Instances of types that represent COM components cannot be cast to different types that represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
what am i doing wrong?
the code is the following:
namespace IEAutomation {
/// <summary>
/// Summary description for IEDriverTest.
/// </summary>
///
using mshtml;
using System.Threading;
using SHDocVw;
public class IEDriverTest {
public IEDriverTest() {
}
public void TestGoogle() {
object o = null;
SHDocVw.InternetExplorer ie = new
SHDocVw.InternetExplorerClass();
IWebBrowserApp wb = (IWebBrowserApp)ie;
wb.Visible = true;
//Do anything else with the window here that you wish
wb.Navigate("https://adwords.google.co.uk/um/Logout", ref o, ref o, ref o, ref o);
while (wb.Busy) { Thread.Sleep(100); }
HTMLDocument document = ((HTMLDocument)wb.Document);
IHTMLElement element = document.getElementById("Email");
HTMLInputElementClass email = (HTMLInputElementClass)element;
email.value = "testtestingtton@gmail.com";
email = null;
element = document.getElementById("Passwd");
HTMLInputElementClass pass = (HTMLInputElementClass)element;
pass.value = "pass";
pass = null;
element = document.getElementById("signIn");
HTMLButtonElementClass subm = (HTMLButtonElementClass)element;//ERROR HERE
subm.click();
}
}
}
A
<button>is not an<input type="submit">or<input type="button">.An
<input>DOM element is represented bymshtml.HTMLInputElementClasswhile a<button>DOM element is represented bymshtml.HTMLButtonElementClass. Thus the cast is invalid as an ButtonElement is not assignable (castable) from an InputElement and the different types represent two distinct HTML entities. A “literal” interpretation of the DOM is exposed.Casting does not (and cannot) change the actual object’s type. The solution is to treat the object for what it is:
mshtml.HTMLInputElement.(It’s a good thing HTMLInputElement also has a
click.)Happy coding.