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