2013-12-16 34 views
4

我需要从webBrowser控件的当前选定选项中选择innerText如何从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的值。

有人能告诉我我做错了什么吗?

回答

6

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

要获得当前选择,您应该调用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; 
} 
+1

谢谢..这个工程!我在下面找到了另一个解决方案,但是这可能比我的解决方案更好... – smitty1

1

不久我张贴了这个后,我想出了一个办法,使这项工作: 我的解决办法

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,弗雷泽的回答也起作用,可能是更好的解决方案。

1
foreach (HtmlElement item in elesex.Children) 
{    
    if (item.GetAttribute("selected") == "True") 
    { 
     sex = item.InnerText; 
    } 
} 
+0

所选属性不会告诉您给定元素是否由用户选择,并且在进行选择时不会更改,它只是指定应在加载页面时预先选择一个选项。在这个范围之外没有用处。 – Fraser

相关问题