Tomaz77
Tomaz77

Reputation: 65

How to insert string into input field using C# in WPF Webbrowser

I have found lots of info on this issue on Stackoverflow, but looks like I'm still missing something. With the Webbrowser I would like to fill in a string into in input field of a certain webpage. By clicking on a button I wish to put some text in the input field.

Here is my code:

using System.Windows.Forms;

and the function:

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        HtmlDocument doc = (HtmlDocument)webBrowser1.Document;
        doc.GetElementsByTagName("input")["username"].SetAttribute("Value", "someString");
    }

The second button handles then the webBbrowser1.Navigate method.

Then I get this error:

{"Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to class type 'System.Windows.Forms.HtmlDocument'. Instances of types that represent COM components cannot be cast to types that do not 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."}

Any ideas? Thanks.

Upvotes: 1

Views: 2515

Answers (1)

Diaa Eddin
Diaa Eddin

Reputation: 419

The error occurs in this line:

HtmlDocument doc = (HtmlDocument)webBrowser1.Document;

Take a look at this. webBrowswer1.Document in WPF returns Microsoft.mshtml.HTMLDocuement so Either add reference to Microsoft.mshtml and then:

private void button2_Click(object sender, RoutedEventArgs e)
{
    var doc = webBrowser1.Document as mshtml.HTMLDocument;
    var input = doc.getElementsByTagName("input");
    foreach (mshtml.IHTMLElement element in input)
    {
        if (element.getAttribute("name") == "username")
        {
            element.setAttribute("value", "someString");
            break;
        }
    }
}

or

private void button2_Click(object sender, RoutedEventArgs e)
{
    dynamic doc = webBrowser1.Document;
    dynamic input = doc.getElementsByTagName("input");
    foreach (dynamic element in input)
    {
        if (element.getAttribute("name") == "username")
        {
            element.setAttribute("value", "someString");
            break;
        }
    }
}

for more information:

Upvotes: 2

Related Questions