C# get element by name

Patric Nøis picture Patric Nøis · Oct 2, 2015 · Viewed 27.2k times · Source

Soo ive figured out how to get element by id, but i dont know how i can get element by name Here is my code:

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

The problem is in my html code only textfield1 is a id but textfield2 is name soo i want to figure out how to get textfield2

Here is my html code:

<html>
    <input type="text" id="textfield1" value="TEXT1"><br>
    <input type="text" name="textfield2" value="TEXT2"><br>
    <input type="submit" value="Submit">
</html>

Answer

Yeldar Kurmangaliyev picture Yeldar Kurmangaliyev · Oct 2, 2015

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);