This documentation is archived and is not being maintained.

HtmlDocument Class

Provides top-level programmatic access to an HTML document hosted by the WebBrowser control.


Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public sealed class HtmlDocument

The HtmlDocument type exposes the following members.

Public propertyActiveElementProvides the HtmlElement which currently has user input focus.
Public propertyActiveLinkColorGets or sets the Color of a hyperlink when clicked by a user.
Public propertyAllGets an instance of HtmlElementCollection, which stores all HtmlElement objects for the document.
Public propertyBackColorGets or sets the background color of the HTML document.
Public propertyBodyGets the HtmlElement for the BODY tag.
Public propertyCookieGets or sets the HTTP cookies associated with this document.
Public propertyDefaultEncodingGets the encoding used by default for the current document.
Public propertyDomainGets or sets the string describing the domain of this document for security purposes.
Public propertyDomDocumentGets the unmanaged interface pointer for this HtmlDocument.
Public propertyEncodingGets or sets the character encoding for this document.
Public propertyFocusedGets a value indicating whether the document has user input focus.
Public propertyForeColorGets or sets the text color for the document.
Public propertyFormsGets a collection of all of the <FORM> elements in the document.
Public propertyImagesGets a collection of all image tags in the document.
Public propertyLinkColorGets or sets the color of hyperlinks.
Public propertyLinksGets a list of all the hyperlinks within this HTML document.
Public propertyRightToLeftGets or sets the direction of text in the current document.
Public propertyTitleGets or sets the text value of the <TITLE> tag in the current HTML document.
Public propertyUrlGets the URL describing the location of this document.
Public propertyVisitedLinkColorGets or sets the Color of links to HTML pages that the user has already visited.
Public propertyWindowGets the HtmlWindow associated with this document.

Public methodAttachEventHandlerAdds an event handler for the named HTML DOM event.
Public methodCreateElementCreates a new HtmlElement of the specified HTML tag type.
Public methodDetachEventHandlerRemoves an event handler from a named event on the HTML DOM.
Public methodEqualsDetermines whether the specified Object is equal to the current Object. (Overrides Object.Equals(Object).)
Public methodExecCommandExecutes the specified command against the document.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodFocusSets user input focus on the current document.
Public methodGetElementByIdRetrieves a single HtmlElement using the element's ID attribute as a search key.
Public methodGetElementFromPointRetrieves the HTML element located at the specified client coordinates.
Public methodGetElementsByTagNameRetrieve a collection of elements with the specified HTML tag.
Public methodGetHashCodeServes as a hash function for a particular type. (Overrides Object.GetHashCode().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInvokeScript(String)Executes an Active Scripting function defined in an HTML page.
Public methodInvokeScript(String, Object[])Executes an Active Scripting function defined in an HTML page.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodOpenNewGets a new HtmlDocument to use with the Write method.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodWriteWrites a new HTML page.

Public eventClickOccurs when the user clicks anywhere on the document.
Public eventContextMenuShowingOccurs when the user requests to display the document's context menu.
Public eventFocusingOccurs before focus is given to the document.
Public eventLosingFocusOccurs while focus is leaving a control.
Public eventMouseDownOccurs when the user clicks the left mouse button.
Public eventMouseLeaveOccurs when the mouse is no longer hovering over the document.
Public eventMouseMoveOccurs when the mouse is moved over the document.
Public eventMouseOverOccurs when the mouse is moved over the document.
Public eventMouseUpOccurs when the user releases the left mouse button.
Public eventStopOccurs when navigation to another Web page is halted.

Public operatorStatic memberEqualityReturns a value that indicates whether the specified HtmlDocument instances represent the same value.
Public operatorStatic memberInequalityReturns a value that indicates whether the specified HtmlDocument instances do not represent the same value.

HtmlDocument provides a managed wrapper around Internet Explorer's document object, also known as the HTML Document Object Model (DOM). You obtain an instance of HtmlDocument through the Document property of the WebBrowser control.

HTML tags inside of an HTML document can be nested inside one another. HtmlDocument thus represents a document tree, whose children are instances of the HtmlElement class. The following code example shows a simple HTML file.

        <DIV name="Span1">Simple HTML Form</DIV>
            <SPAN name="TextLabel">Enter Your Name:</SPAN>
            <INPUT type="text" size="20" name="Text1">

In this example, HtmlDocument represents the entire document inside the HTML tags. The BODY, DIV, FORM and SPAN tags are represented by individual HtmlElement objects.

There are several ways you can access the elements in this tree. Use the Body property to access the BODY tag and all of its children. The ActiveElement property gives you the HtmlElement for the element on an HTML page that has user input focus. All elements within an HTML page can have a name; the All collection provides access to each HtmlElement using its name as an index. GetElementsByTagName will return an HtmlElementCollection of all HtmlElement objects with a given HTML tag name, such as DIV or TABLE. GetElementById will return the single HtmlElement corresponding to the unique ID that you supply. GetElementFromPoint will return the HtmlElement that can be found on the screen at the supplied mouse pointer coordinates.

You can also use the Forms and Images collection to iterate through elements that represent user input forms and graphics, respectively.

HtmlDocument is based on the unmanaged interfaces implemented by Internet Explorer's DHTML DOM: IHTMLDocument, IHTMLDocument2, IHTMLDocument3, and IHTMLDocument4. Only the most frequently used properties and methods on these unmanaged interfaces are exposed by HtmlDocument. You can access all other properties and methods directly using the DomDocument property, which you can cast to the desired unmanaged interface pointer.

An HTML document may contain frames, which are different windows inside of the WebBrowser control. Each frame displays its own HTML page. The Frames collection is available through the Window property. You may also use the Window property to resize the displayed page, scroll the document, or display alerts and prompts to the user.

HtmlDocument exposes the most common events you would expect to handle when hosting HTML pages. For events not exposed directly by the interface, you can add a handler for the event using AttachEventHandler.

HTML files may contain SCRIPT tags that encapsulate code written in one of the Active Scripting languages, such as JScript or VBScript. The InvokeScript method provides for execution of properties and methods defined in a SCRIPT tag.


While most of the properties, methods, and events on HtmlDocument have kept the same names as they have on the unmanaged DOM, some have been changed for consistency with the .NET Framework.

The following code example uses data from the Northwind database to create an HTML TABLE dynamically using CreateElement. The AppendChild method is also used, first to add cells (TD elements) to rows (TR elements), then to add rows to the table, and finally to append the table to the end of the current document. The code example requires that your application has a WebBrowser control named WebBrowser1. The code should be called after a document has been loaded.

private void DisplayCustomersTable()
    DataSet customersSet = new DataSet();
    DataTable customersTable = null;
    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Customers", "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");
    customersTable = customersSet.Tables[0];

    if (webBrowser1.Document != null)
        HtmlElement tableRow = null;
        HtmlElement headerElem = null;

        HtmlDocument doc = webBrowser1.Document;
        HtmlElement tableElem = doc.CreateElement("TABLE");

        HtmlElement tableHeader = doc.CreateElement("THEAD");
        tableRow = doc.CreateElement("TR");

        foreach (DataColumn col in customersTable.Columns)
            headerElem = doc.CreateElement("TH");
            headerElem.InnerText = col.ColumnName;

        // Create table rows.
        HtmlElement tableBody = doc.CreateElement("TBODY");
        foreach (DataRow dr in customersTable.Rows)
            tableRow = doc.CreateElement("TR");
            foreach (DataColumn col in customersTable.Columns)
                Object dbCell = dr[col];
                HtmlElement tableCell = doc.CreateElement("TD");
                if (!(dbCell is DBNull))
                    tableCell.InnerText = dbCell.ToString();

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.