C# get element by name
Asked Answered
A

3

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>
Apposite answered 2/10, 2015 at 9:26 Comment(2)
What is webBrowser1, and Document? What library/framweork are you using?Leventhal
@kai It is a simple System.Windows.Forms.WebBrowser and its HtmlDocument.Sock
S
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);
Sock answered 2/10, 2015 at 9:35 Comment(0)
C
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);
}
Chancechancel answered 2/10, 2015 at 9:28 Comment(5)
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?Marry
For some reason, I do not have such method... I am using .NET 4.5.Sock
HtmlDocument contains no such method, this doesn't compile.Leventhal
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?Weathering
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.Cuspidor
M
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]
Mccleary answered 2/10, 2015 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.