[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Generate and display HTML in C#

Generate and display HTML

This example actually does two things: it makes a WebBrowser control navigate to the user's home page, and it shows how to generate and display HTML in the WebBrowser control at run time. When the program starts, it uses the following code to navigate to the user's home page.

// Start at home. private void Form1_Load(object sender, EventArgs e) { wbrDisplay.GoHome(); }

This code simply calls the WebBrowser control's GoHome method.

When you click the Set Contents button, the program uses the following code to display the HTML code in the upper text box.

// Set the HTML contents. private void btn_Click(object sender, EventArgs e) { HtmlDocument doc = wbrDisplay.Document; doc.Body.InnerHtml = txtHtml.Text; }

This code simply gets the WebBrowser control's Document object (which represents the HTML document that is currently displayed) and sets its InnerHtml property equal to the text in the program's TextBox. That changes the document so it holds the HTML text and that makes the control display the HTML data.

Note that the WebBrowser control's Document property is not initially defined. The program must load something into the WebBrowser and wait until it has finished loading before it tries to use the Document object. For example, if you move the code that displays the HTML text into the program's Load event handler, the program crashes because the Document object is null at that time.

That's why this program starts by going to the user's home page. That loads the Document object.

Alternatively you can navigate to about:blank to make the WebBrowser display a blank document.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.