在 WebBrowser 控件中设置 TextArea 的值 (C#/.NET)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/580052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:05:52  来源:igfitidea点击:

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

c#.nethtmlwebbrowser-control

提问by

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

我希望使用 .NET WebBrowser Control 设置 TextArea 的值。

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.

我尝试在 TextArea 上使用类似的代码(使用 GetElementById),但没有记住 TextArea 输入类型不包含“Value”属性。我还尝试设置 TextArea 的 InnerHtml 和 InnerText,但是在尝试设置 TextArea 输入的值时,编译器继续抛出空引用异常错误或索引越界错误。

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

有没有人知道如何使用 WebBrowser 控件在 TextArea 中设置文本?任何建议将不胜感激!

回答by Daniel LeCheminant

Suppose you had the following HTML:

假设您有以下 HTML:

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

You can set the text in the textarealike this:

您可以textarea像这样设置文本:

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

回答by Robert

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

几点,以防万一你还没有意识到这些:

  • GetElementByIdwill only return a single item or null, it is not a collection.
  • index out of bounds errorswill 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.Documentproperty so theres no need to access the All[]collection.
  • GetElementById只会返回单个项目或 null,它不是一个集合。
  • 如果您尝试将元素从 WebBrowser 控件的一个实例插入到 WebBrowser 控件的另一个实例的元素中,则会引发索引越界错误
  • GetElementBy ..可以从直馏WebBrowser.Document属性,因此世界上没有其他需要访问的所有[]集合。