LBogaardt LBogaardt - 1 year ago 958
C# Question

WPF - Webbrowser - getElementById

In a WPF application, I have a webbrowser called WebBrowser1. This refers to an HTML page which contains a TextArea to which users can input text.

<textarea class="myStudentInput" id="myStudentInput1">
Text to be copied

I wish to get this text and potentially also set this text.

I have tried something similar to the javascript way of writing it:


such as

HtmlElement textArea = webBrowser1.Document.All["myStudentInput1"];

dynamic textArea = WebBrowser1.Document.GetElementsByID("myStudentInput1").InnerText;

but it doesn't work.

Answer Source

The following solution in Visual Studio 2015 WPF Application works for me.

First, add a reference to the Microsoft HTML COM Library. This is on the COM tab, when you do an "Add Reference" in your project.

Then add the code:

<Window x:Class="WpfApplication3.MainWindow"
        Title="MainWindow" Height="600" Width="800">
        <WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Left" Height="480" Margin="10,10,0,0" VerticalAlignment="Top" Width="770" Source="E:\Others\Dropbox\Programming\Questions.html"/>
        <Button x:Name="mySetQuestionButton" Content="Set Question" HorizontalAlignment="Left" Margin="200,520,0,0" VerticalAlignment="Top" Width="75" Click="mySetQuestion"/>
        <Button x:Name="myGetAnswerButton" Content="Get Answer" HorizontalAlignment="Left" Margin="350,520,0,0" VerticalAlignment="Top" Width="75" Click="myGetAnswer"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="600,520,0,0" TextWrapping="Wrap" Text="Hello2" VerticalAlignment="Top"/>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication3
    public partial class MainWindow : Window
        public MainWindow()
        private void mySetQuestion(object sender, EventArgs e)
            mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
            mshtml.IHTMLElement textArea = document.getElementById("myQuestion1");
            textArea.innerHTML = "What is 1+1?";
        private void myGetAnswer(object sender, EventArgs e)
            mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
            mshtml.IHTMLElement textArea = document.getElementById("myStudentInput1");
            textBlock.Text = textArea.innerHTML;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download