Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to fill inputs via webbrowser. When i try to getelementbyname i am getting null value. Could you help me solve this problem please?

Here is html code of a website which i navigated:
<input onfocus="showInfoBox(this, "Varchar(100) Latin capital letters only (A-Z) and spaces between surnames")" onblur="hideInfoBox()" value="" name="Surname"><input>


Here is my code:
C#
public HtmlElementCollection GetElemByName(string name)
{
    if (webBrowser1.Document == null)
        return null;

    HtmlDocument doc = webBrowser1.Document;

    return doc.All.GetElementsByName(name);
}


private void button2_Click(object sender, EventArgs e)
{
    HtmlElementCollection col = GetElemByName("Surname");
    if (col != null && col.Count > 0)
    {
        col[0].SetAttribute("Surname", "My Surname");
    }
}
Posted
Comments
Zoltán Zörgő 17-Jan-15 6:51am    
Any progress?
Member 10623326 17-Jan-15 11:00am    
I solved my problem by using GetElementsByTagName and added to solution. Thanks!

Make sure, that you try to access the elements only when DOM is ready - be aware, that the control is running asycronously. I don't know if you are trying this from console or from windows forms, but the apprach is highlighted here: How Use WebBrowser without winform[^]. It will work, it worked with my test.

Still, you better not use WebBrowser control for that. If you need to mock the user actions in a browser, you can either automate the browser (IE for example) with better tools, like Harness[^] or WatiN[^], or you can forget the browser alltogether and use WebClient[^] or HttpWebRequest[^] to interact with the server on http level. If you want to do some batch or background job, this is the way. You will most likelly need to do some sniffing (with Fiddler[^] for example) to see what's actually sent and received by the client, but if it's not an ASP.NET Web Forms application with random autogenerated ID's and names, it will be not hard to get the idea quickly. This way you have all the control and consume considerably less resources.
 
Share this answer
 
v2
C#
static HtmlElementCollection FillInputs(WebBrowser browser)
{
var input = browser.Document.GetElementsByTagName("input");
foreach (HtmlElement element in input)
{
    if (element.GetAttribute("name") == "Surname")
    {
         element.SetAttribute("value", "My Surname");
    }
}
return input;
}

C#
private void button2_Click(object sender, EventArgs e)
{
    var collection = FillInputs(webBrowser1);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900