2010-05-16 43 views
0

在C#WPF程序我'尝试设置其上定义一个HTML元素Text值:设置HTML文本元素值

<input name="tbBName" type="text" id="tbBName" tabindex="1" /> 

我试过如下:

mshtml.HTMLDocument doc = (mshtml.HTMLDocument)webBrowser1.Document; 
mshtml.HTMLInputTextElement tbName = (mshtml.HTMLInputTextElement)doc.getElementsByName("tbBName"); 
tbName.value = "Test"; 

但我得到以下异常:

Unable to cast COM object of type 'System.__ComObject' to interface type 'mshtml.HTMLInputTextElement'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3050F520-98B5-11CF-BB82-00AA00BDCE0B}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

我知道它说什么,但我不知道我可以使用哪个对象来访问文本框。

我在做什么错?

回答

0

您使用HTML Agility Pack解析完整的HTML(由WebBrowser控制原样)。

您可以使用XPath语法来查询它,并以类似于XmlDocument API的方式公开HTML。

+0

谢谢你Oded我会看看这个包。 但我没有一个简单的方法与我正在尝试的代码? – Gpx 2010-05-16 07:03:02

+0

@Gpx - 不确定。我注意到的一件事是你正在得到一个_collection_('getElementsByName'返回一个集合),你试图强制它成为一个单一的元素。尝试选择第一个结果。 – Oded 2010-05-16 07:39:00

+0

On mshtml.HTMLElementCollection collection =(mshtml.HTMLElementCollection)document.getElementsByName(“tbName”); 我得到同样的例外。 – Gpx 2010-05-16 08:00:08

0

你知道,如果你使用jQuery 我可以告诉你,它很容易

$('#tbBName').val('value here'); 
+0

嘿穆斯塔法, 我不能够访问的一页的代码和我不想要写jQuery的东西。 它是一个用excel文件中的值填充页面的texboxes的工具。 所以你有任何C#的想法? – Gpx 2010-05-16 06:56:53

0

我发现getElementsByName是不可靠的,直接在文档中使用时(使用从C++)

所以与俄德有关结果提到是一个集合的问题一起,你可能会想尝试一些像以下结构。 (未经测试/轮廓只)

mshtml.HTMLDocument doc = (mshtml.HTMLDocument)webBrowser1.Document; 
mshtml.ElementCollection col = doc.getAll(); 
Dispatch disp = col.namedItem("tbBName"); 
// in C++ this can return either a collection or an item 
try{ // collection 
    mshtml.ElementCollection col2 = (mshtml.ElementCollection)disp; 
    for(index = 0; index < col2.length; ++index) { 
    mshtml.HTMLInputTextElement tbName = (mshtml.HTMLInputTextElement)col2[index]; 
    tbName.value = "Test"; 
} 
try{ // item 
    mshtml.HTMLInputTextElement tbName = (mshtml.HTMLInputTextElement)disp; 
    tbName.value = "Test"; 
}