2013-12-16 33 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

相關問題