【问题标题】:How to get the innerText from currently selected option in a webBrowser control如何从 webBrowser 控件中的当前选定选项中获取 innerText
【发布时间】:2014-01-03 08:58:29
【问题描述】:

我需要从 webBrowser 控件中当前选择的选项中选择innerText

这是 html 的表示:

<SELECT ID="F8">
<OPTION VALUE="option1">option1</OPTION>
<OPTION VALUE="option2" selected>option2</OPTION>
<OPTION VALUE="option3">option3</OPTION>
</SELECT>

这是我正在尝试的:

if (webBrowser1.Document.GetElementById("F8") != null)
{
    HtmlElement selectF8 = webBrowser1.Document.GetElementById("F8");
    foreach (HtmlElement item in selectF8.Children ) 
    {
        if (item.GetAttribute("selected") != null)
        {
            assigneeText.Text = item.InnerText;
        }
    }
}

...但它完全忽略了 if 语句并始终将 assigneeText.Text 的值分配给 option3 而不是选定的 option2 的值。

谁能告诉我我做错了什么?

【问题讨论】:

    标签: c# html webbrowser-control innertext


    【解决方案1】:

    当您更改控件上的选择时,选定的属性不会更新。用于定义控件首次显示时选择的项目(默认选项)。

    要获得当前选择,您应该调用selectedIndex 方法来找出选择了哪个项目。

    HtmlElement element = webBrowser1.Document.GetElementById("F8");
    object objElement = element.DomElement;
    object objSelectedIndex = objElement.GetType().InvokeMember("selectedIndex",
    BindingFlags.GetProperty, null, objElement, null);
    int selectedIndex = (int)objSelectedIndex;
    if (selectedIndex != -1)
    {
      assigneeText.Text = element.Children[selectedIndex].InnerText;
    }
    

    如果您使用的是 c# 4,您还可以使用 DLR 来避免使用反射。

    var element = webBrowser1.Document.GetElementById("F8");
    dynamic dom = element.DomElement;
    int index = (int)dom.selectedIndex();
    if (index != -1)
    {
      assigneeText.Text = element.Children[index].InnerText;
    }
    

    【讨论】:

    • 谢谢..这行得通!我在下面找到了另一个解决方案,但这可能比我的解决方案更好......
    【解决方案2】:

    在发布此消息后不久,我想出了一种方法来完成这项工作: 我的解决方案是

    HtmlElement selectF8 = webBrowser1.Document.GetElementById("F8");
    foreach (HtmlElement item in selectF8.Children)
    {
        if (item.GetAttribute("value") == webBrowser1.Document.GetElementById("F8").GetAttribute("value"))
        {
            assigneeText.Text = item.InnerText;
        }
    }
    

    这似乎可行,虽然是 C# 和 .net 的新手,但 Fraser 的答案也可行,可能是更好的解决方案。

    【讨论】:

      【解决方案3】:
      foreach (HtmlElement item in elesex.Children)
      {              
          if (item.GetAttribute("selected") == "True")
          {
              sex = item.InnerText;
          }
      }
      

      【讨论】:

      • selected 属性不会告诉您给定元素是否被用户选中 - 并且在进行选择时不会更改,它只是指定在页面加载。在这个范围之外它没有用处。
      猜你喜欢
      • 2011-05-14
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2019-08-20
      相关资源
      最近更新 更多