从webbrowser中选择下拉选项

时间:2012-09-04 06:15:45

标签: c#

我的目标我需要选择第二个选项。

我尝试了以下方法,无法设置所选值。没有出现错误,选择就不会发生。我自己非常熟悉HTML,我知道“selected”和“selected =”选择“'工作但不确定为什么它不能使用我的C#代码。可能有什么不对?

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>

2 个答案:

答案 0 :(得分:7)

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

  }

答案 1 :(得分:2)

如果代码位于合适的位置,您的代码应该正常工作,例如:button1_Click事件,webBrowser1_DocumentCompleted事件等。

相关问题