6

So I've figured out how to get an element by id, but I don't know how I can get an element by name.

private void SendData()
{
    webBrowser1.Document.GetElementById("textfield1")
        .SetAttribute("value", textBox1.Text);
    webBrowser1.Document.GetElementById("textfield2")
        .SetAttribute("value", textBox1.Text);
}

The problem is in HTML textfield1 is an id but textfield2 is a name. So I want to figure out how to get textfield2:

<html>
    <input type="text" id="textfield1" value="TEXT1"><br>
    <input type="text" name="textfield2" value="TEXT2"><br>
    <input type="submit" value="Submit">
</html>
Toni
  • 1,555
  • 4
  • 15
  • 23
Patric Nøis
  • 208
  • 2
  • 8
  • 27

3 Answers3

12

You can get an HtmlElementCollection - for example, using GetElementsByTagName method. Then, HtmlElementCollection has GetElementsByName method:

webBrowser1.Document
    .GetElementsByTagName("input")
    .GetElementsByName("textfield2")[0]
        .SetAttribute("value", textBox1.Text);
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
4

You can use HtmlElementCollection.GetElementsByName to take the value of the elements

webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox1.Text);

EDIT

foreach (HtmlElement he in webBrowser1.Document.All.GetElementsByName("textfield2"))
{
    he.SetAttribute("value", textBox1.Text);
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • Are you sure that the code works as intended? .GetElementsByName SHOULD return an array so you would have to use [0] before the .SetAttribute or am I mistaken there? – Thomas Oct 02 '15 at 09:31
  • For some reason, I do not have such method... I am using .NET 4.5. – Yeldar Kurmangaliyev Oct 02 '15 at 09:31
  • `HtmlDocument` contains no such method, this doesn't compile. – sara Oct 02 '15 at 09:34
  • webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox2.Text); webBrowser1.Document.GetElementsByName("login_buton").InvokeMember("click"); i tryed this but cant get it to work do i gota add something inn my codes or? – Patric Nøis Oct 02 '15 at 09:37
  • hi, webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox2.Text); will get elements collections not a single element like in getelementbyid. please try webBrowser1.Document.GetElementsByName("textfield2")[0] .SetAttribute("value", textBox1.Text); If not working can you post what exactly the error code is. I'm wondering if the html is fully loaded. – Padhu Oct 02 '15 at 09:50
1

You can't access the elements directly by name, but you could access it by finding the input tags first, and indexing into the result to find the tags by name.

webBrowser1.Document.GetElementsByTagName("input")["textfield2"]

or

webBrowser1.Document
    .GetElementsByTagName("input")
    .GetElementsByName("textfield2")[0]
Shanaka Rusith
  • 421
  • 1
  • 4
  • 19