5

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

我尝试了以下方法,但无法设置选定值。没有错误出现,选择只是没有发生。我自己对 HTML 非常熟悉,我知道“selected”和“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>
4

2 回答 2

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

  }
于 2012-12-19T16:28:07.467 回答
3

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

于 2012-09-04T07:02:43.887 回答