WebBrowser control HTMLDocument automate selecting option drop-down

CWinKY picture CWinKY · Feb 28, 2010 · Viewed 45.2k times · Source

I'm trying to automate in a WinForm using a WebBrowser control to navigate and pull report info from a website. You can enter values in textboxes and invoke the click events for buttons and links, but I have not figured out how select a option drop-down .... in a automated way. Anybody recommend how to select a item from a drop-down, given this html example:

<SELECT id="term_id" size="1" name="p_term_in"><option value="">Select Another Term<option value="201050">Summer 2010<option value="201010">Spring 2010<option value="200980">Fall 2009</SELECT>

For others that can learn from entering values to textboxes and invoking click events here's how you do it:

webBrowser1.Document.GetElementById("<HTML ELEMENT NAME>").SetAttribute("value", "THE NAME");

Invoke button or hyperlink click:

webBrowser1.Document.GetElementById("<BUTTON>").InvokeMember("click");

So I've solved entering values and invoking click, but I have not solved selecting a drop-down value.

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 28, 2010

Assuming you have the following select in the HTML:

<select id="term_id" size="1" name="p_term_in">
    <option value="">Select Another Term
    <option value="201050">Summer 2010
    <option value="201010">Spring 2010
    <option value="200980">Fall 2009
</select>

This should allow you to preselect the third value:

webBrowser1.Document.GetElementById("term_id").SetAttribute("value", "201010");