smi*_*ty1 4 html c# webbrowser-control innertext
我需要innerText从webBrowser控件中的当前选定选项中选择.
这是html的表示:
<SELECT ID="F8">
<OPTION VALUE="option1">option1</OPTION>
<OPTION VALUE="option2" selected>option2</OPTION>
<OPTION VALUE="option3">option3</OPTION>
</SELECT>
Run Code Online (Sandbox Code Playgroud)
这是我正在尝试的:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
...但它完全忽略if语句并始终指定assigneeText.Text值option3而不是所选值option2.
有人可以告诉我我做错了什么吗?
更改控件上的选择时,所选属性不会更新.它用于在首次显示控件时定义所选项目(默认选项).
要获取当前选择,您应调用该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;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5559 次 |
| 最近记录: |