Set Value of a TextArea inside a WebBrowser Control (C# / .NET)

旧巷老猫 提交于 2019-11-28 01:58:24

问题


I'm looking to set the value of a TextArea using the .NET WebBrowser Control.

I have been able to set the values of textboxes using the following code (replace "username" with the name of the texbox):

webBrowser1.Document.All.GetElementsByName("username")[0].SetAttribute("Value", "SomeUser");

I tried using similar code on a TextArea (using GetElementById) and failed to remember that TextArea input types do not contain a "Value" attribute. I have also tried setting the InnerHtml and InnerText of the TextArea but the compiler continues to throw null reference exception errors or index out of bounds errors when trying set the value of the TextArea input.

Does anyone have any idea on how to set the text inside a TextArea using the WebBrowser Control? Any advice would be much appreciated!


回答1:


Suppose you had the following HTML:

<html>
<body>
   <textarea id='foo'>Testing</textarea>
</body>
</html>

You can set the text in the textarea like this:

HtmlElement textArea = webBrowser1.Document.All["foo"];
if (textArea != null)
{
    textArea.InnerText = "This is a test";
}



回答2:


A couple of points just in case you haven't realised these:

  • GetElementById will only return a single item or null, it is not a collection.
  • index out of bounds errors will be thrown if you try and insert elements from one instance of the WebBrowser control into elements of another instance of the WebBrowser control.
  • The GetElementBy.. can be run straight from the WebBrowser.Document property so theres no need to access the All[] collection.


来源:https://stackoverflow.com/questions/580052/set-value-of-a-textarea-inside-a-webbrowser-control-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!