Choosing a drop-down list option from a web browser

My goal I need to choose the second option.

I tried the following approach and cannot set the selected value. The error does not appear, the choice simply does not occur. I myself am very familiar with HTML, I know that "selected" and "selected =" selected "are selected, but I do not know why it does not work with my C # code. What could be wrong?

webBrowser1.Document.GetElementById("field_gender1"). Children[1].SetAttribute("selected", "selected"); 

HTML

 <select name="gender1" id="field_gender1" class="select"> <option selected="selected" value="1">val1</option> <option value="2">val2</option> </select> 
+4
source share
2 answers

Your code should work if it is in a suitable place, for example: button1_Click, event webBrowser1_DocumentCompleted, etc.

+2
source

Do it from WebBrowser_DocumentComplete (...)

 var htmlDocument = webBrowser1.Document as IHTMLDocument2; if (htmlDocument != null) { var dropdown = ((IHTMLElement)htmlDocument.all.item("field_gender1")); var dropdownItems = (IHTMLElementCollection)dropdown.children; foreach(IHTMLElement option in dropdownItems) { var value = option.getAttribute("value").ToString(); if(value.Equals("2")) option.setAttribute("selected", "selected"); } } 
+6
source

Source: https://habr.com/ru/post/1432200/


All Articles