Bewerken

Share via


HtmlDocument Class

Definition

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

public ref class HtmlDocument sealed
public sealed class HtmlDocument
type HtmlDocument = class
Public NotInheritable Class HtmlDocument
Inheritance
HtmlDocument

Examples

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;");
    sda.Fill(customersTable);
    customersTable = customersSet.Tables[0];

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

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

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

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

        // Create table rows.
        HtmlElement tableBody = doc.CreateElement("TBODY");
        tableElem.AppendChild(tableBody);
        foreach (DataRow dr in customersTable.Rows)
        {
            tableRow = doc.CreateElement("TR");
            tableBody.AppendChild(tableRow);
            foreach (DataColumn col in customersTable.Columns)
            {
                Object dbCell = dr[col];
                HtmlElement tableCell = doc.CreateElement("TD");
                if (!(dbCell is DBNull))
                {
                    tableCell.InnerText = dbCell.ToString();
                }
                tableRow.AppendChild(tableCell);
            }
        }
    }
}
Private Sub DisplayCustomersTable()
    ' Initialize the database connection.
    Dim CustomerData As New DataSet()
    Dim CustomerTable As DataTable

    Try
        Dim DBConn As New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")
        Dim DBQuery As New SqlDataAdapter("SELECT * FROM CUSTOMERS", DBConn)
        DBQuery.Fill(CustomerData)
    Catch dbEX As DataException

    End Try

    CustomerTable = CustomerData.Tables("Customers")

    If (Not (WebBrowser1.Document Is Nothing)) Then
        With WebBrowser1.Document
            Dim TableElem As HtmlElement = .CreateElement("TABLE")
            .Body.AppendChild(TableElem)

            Dim TableRow As HtmlElement

            ' Create the table header. 
            Dim TableHeader As HtmlElement = .CreateElement("THEAD")
            TableElem.AppendChild(TableHeader)
            TableRow = .CreateElement("TR")
            TableHeader.AppendChild(TableRow)

            Dim HeaderElem As HtmlElement
            For Each Col As DataColumn In CustomerTable.Columns
                HeaderElem = .CreateElement("TH")
                HeaderElem.InnerText = Col.ColumnName
                TableRow.AppendChild(HeaderElem)
            Next

            ' Create table rows.
            Dim TableBody As HtmlElement = .CreateElement("TBODY")
            TableElem.AppendChild(TableBody)
            For Each Row As DataRow In CustomerTable.Rows
                TableRow = .CreateElement("TR")
                TableBody.AppendChild(TableRow)
                For Each Col As DataColumn In CustomerTable.Columns
                    Dim Item As Object = Row(Col)
                    Dim TableCell As HtmlElement = .CreateElement("TD")
                    If Not (TypeOf (Item) Is DBNull) Then
                        TableCell.InnerText = CStr(Item)
                    End If
                    TableRow.AppendChild(TableCell)
                Next
            Next

        End With
    End If
End Sub

Remarks

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.

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

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.

Note

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.

Properties

ActiveElement

Provides the HtmlElement which currently has user input focus.

ActiveLinkColor

Gets or sets the Color of a hyperlink when clicked by a user.

All

Gets an instance of HtmlElementCollection, which stores all HtmlElement objects for the document.

BackColor

Gets or sets the background color of the HTML document.

Body

Gets the HtmlElement for the BODY tag.

Cookie

Gets or sets the HTTP cookies associated with this document.

DefaultEncoding

Gets the encoding used by default for the current document.

Domain

Gets or sets the string describing the domain of this document for security purposes.

DomDocument

Gets the unmanaged interface pointer for this HtmlDocument.

Encoding

Gets or sets the character encoding for this document.

Focused

Gets a value indicating whether the document has user input focus.

ForeColor

Gets or sets the text color for the document.

Forms

Gets a collection of all of the <FORM> elements in the document.

Images

Gets a collection of all image tags in the document.

LinkColor

Gets or sets the color of hyperlinks.

Links

Gets a list of all the hyperlinks within this HTML document.

RightToLeft

Gets or sets the direction of text in the current document.

Title

Gets or sets the text value of the <TITLE> tag in the current HTML document.

Url

Gets the URL describing the location of this document.

VisitedLinkColor

Gets or sets the Color of links to HTML pages that the user has already visited.

Window

Gets the HtmlWindow associated with this document.

Methods

AttachEventHandler(String, EventHandler)

Adds an event handler for the named HTML DOM event.

CreateElement(String)

Creates a new HtmlElement of the specified HTML tag type.

DetachEventHandler(String, EventHandler)

Removes an event handler from a named event on the HTML DOM.

Equals(Object)

Tests the object for equality against the current object.

ExecCommand(String, Boolean, Object)

Executes the specified command against the document.

Focus()

Sets user input focus on the current document.

GetElementById(String)

Retrieves a single HtmlElement using the element's ID attribute as a search key.

GetElementFromPoint(Point)

Retrieves the HTML element located at the specified client coordinates.

GetElementsByTagName(String)

Retrieve a collection of elements with the specified HTML tag.

GetHashCode()

Retrieves the hash code for this object.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
InvokeScript(String, Object[])

Executes an Active Scripting function defined in an HTML page.

InvokeScript(String)

Executes an Active Scripting function defined in an HTML page.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
OpenNew(Boolean)

Gets a new HtmlDocument to use with the Write(String) method.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
Write(String)

Writes a new HTML page.

Operators

Equality(HtmlDocument, HtmlDocument)

Returns a value that indicates whether the specified HtmlDocument instances represent the same value.

Inequality(HtmlDocument, HtmlDocument)

Returns a value that indicates whether the specified HtmlDocument instances do not represent the same value.

Events

Click

Occurs when the user clicks anywhere on the document.

ContextMenuShowing

Occurs when the user requests to display the document's context menu.

Focusing

Occurs before focus is given to the document.

LosingFocus

Occurs while focus is leaving a control.

MouseDown

Occurs when the user clicks the left mouse button.

MouseLeave

Occurs when the mouse is no longer hovering over the document.

MouseMove

Occurs when the mouse is moved over the document.

MouseOver

Occurs when the mouse is moved over the document.

MouseUp

Occurs when the user releases the left mouse button.

Stop

Occurs when navigation to another Web page is halted.

Applies to

See also