Recently I’ve been playing around with a webbrowser control to automate my interaction with a website for testing purposes. I am using C# and DOT NET.

I found it a bit difficult to change the value of an HTML combobox (i.e. dropdown), but as it turns out it’s rather easy.I used the following code to change the value of a combobox named: “test” to the value 12.

foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("select"))
 {
 if (el.Name == "test")
 {
 foreach (HtmlElement comboItem in el.Children)
 {
 Console.WriteLine(comboItem.InnerText + " " + comboItem.GetAttribute("Selected"));
if (comboItem.InnerText == "12")
 {
 comboItem.SetAttribute("Selected", "True");
 }
 }
 }
}

This code was used for the following HTML:

<select name="test">
  <option value="10" SELECTED>10&</option>
  <option value="11">11</option>
  <option value="12">12</option>
  <option value="13">13</option>
  <option value="14">14</option>
</select>

Finally the following code was required to press the “Submit” button:

foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("input"))
{
if (el.Name.ToLower() == "submit")
{
el.InvokeMember("click");
}
}

2 thoughts on “Selecting the value of an HTML combobox programmatically using a WebBrowser Control

  1. thanks for your code
    I follow it step by step and it changes the value of the combo, but it doesn’t display the changed value, even if the “selected” property changed from false to true.
    I searched such prob in the net, and I find your post the best one, but unfortunately is sill unaccomplished.

    Reply

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

Page last modified: 22:36 on May 3, 2020 (UTC+2)