2012-03-18 109 views
1

假設我有以下HTML:如何通過C#將文本插入文本區域與Forms.WebBrowser

<html> 
<body> 
    <textarea id="foo"></textarea> 
</body> 
</html> 

如何將文本插入到C#Htmldocument textarea的?

setattribute()方法不工作,因爲沒有value字段textarea

那麼如何通過C#插入texttextarea

任何意見是非常感謝!
在此先感謝。

回答

0

首先,爲您的項目添加對Microsoft.mshtml的引用,或者如果它不在列表中,則文件爲C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll。然後,C#代碼看起來是這樣的:

string myId = "foo"; 
string myNewValue = "This goes in the Text Area!"; 

IHTMLDocument2 htmlDoc = webBrowser1.Document.DomDocument as IHtmlDocument2; 
if (htmlDoc != null) 
{ 
    var textAreaType = typeof(IHTMLTextAreaElemnt); 
    IHTMLTextAreaElement htmlTextArea = 
    htmlDoc.All 
      .FirstOrDefault(x => textAreaType.IsAssignableFrom(x) 
           && ((IHTMLElement)x).id == myId) 
      as IHTMLTextAreaElement; 
    if (htmlTextArea != null) 
    { 
    htmlTextArea.value = myNewValue; 
    } 
} 
+0

謝謝埃裏克,但你可以指定C#和代碼,爲我增加了從Microsoft.mshtml.tlb refrence不是微軟\ Windows \ System32' 下。。 '.. \ Microsoft Visual Studio 10.0 \ Visual Studio Tools for Office \ PIA \ Common文件夾中的mshtml.dll。 – Murthy 2012-03-18 09:31:42

+0

我已根據您的評論更新。 – 2012-03-18 09:44:46

+0

謝謝你的幫助Erik,但是在添加IHTMLDocument2的引用之後,它仍然顯示錯誤「無法找到類型或名稱空間名'IHTMLTextAreaElement'(你是否缺少using指令或程序集引用?)」,我需要安裝任何SDK的?或者除了HTML文檔之外還有其他方法嗎? – Murthy 2012-03-18 10:00:29