Koray
Koray

Reputation: 397

Webbrowser getelementbyname?

<input onfocus="showInfoBox(this, "Varchar(100) Latin capital letters only (A-Z) and spaces between surnames")" onblur="hideInfoBox()" value="" name="Surname"><input>

I need to fill inputs via webbrowser. When i try to fill i am getting System.ArgumentOutOfRangeException error. How can i fill this input area?

This is my code

webBrowser1.Document.GetElementsByTagName("Surname")[0].SetAttribute("MySurName", "true");

Upvotes: 1

Views: 6429

Answers (3)

Paul
Paul

Reputation: 64

This should work for you:

    Dim inp As HtmlElement
    For Each inp In wb.Document.GetElementsByTagName("input")
    If inp.GetAttribute("name") = "surname" Then
    inp.SetAttribute("value", "your text")
    End If
    Next

Upvotes: 1

mybirthname
mybirthname

Reputation: 18127

Your code is invalid. When you are using GetElementByTagName you need to search by the Tag name. In your case is Tag Name is input. You can check this article.

Also you have a typo in the name you don't have ". See name=Surname". You can try to use GetElementByName method. Check this article. Be aware you are missing the input type. Search google for the didferent input types !

public HtmlElementCollection GetElemByName(string name)
{
    if (webBrowser1.Document == null)
         return null;

        HtmlDocument doc = webBrowser1.Document;

        return doc.All.GetElementsByName(name);                 
}

After that you are calling the method;

HtmlElementCollection col = GetElemByName("SurName");
if(col != null && col.Count > 0)
    col[0].SetAttribute("AnyAttribute", value); // be aware THERE IS NO ATTRIBUTE MySurName !!!

I don't know if you want to loop your elements, if you have more than one element with the same name. Also make difference between attribute and attribute value. If you want your name to became MySurName, you need this

col[0].SetAttribute("name", "MySurName");

Upvotes: 1

Alexander Dayan
Alexander Dayan

Reputation: 2924

The reason of exception is that the function GetElementsByTagName founds zero element, so the collection is empty and so the exception threw when you try to access element number 1 of empty collection.

To get an element by its name like "Surname" you should use GetElementsByName instead of GetElementsByTagName which should be used for tags line 'input'.

However, no function will return a good result because the html you provided is completely malformed.

  1. The 'input' tag is self-closed and should look as following: <input .... />. Remove unnecessary additional '<input>' at the end!
  2. Be careful with quotation marks. In should be onfocus="showInfoBox(this, 'Varchar(100) Latin capital letters only (A-Z) and spaces between surnames')"; name=Surname" should be name="Surname".
  3. input must have type property (<input type='text' or <input type='checkbox', etc)

Upvotes: 1

Related Questions