Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get element by name

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>
like image 488
Patric Nøis Avatar asked Oct 02 '15 09:10

Patric Nøis


2 Answers

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);
like image 53
Yeldar Kurmangaliyev Avatar answered Sep 17 '22 19:09

Yeldar Kurmangaliyev


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);
}
like image 43
Mohit S Avatar answered Sep 19 '22 19:09

Mohit S