TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# HtmlTextWriter Use

This C# tutorial shows the HtmlTextWriter type. It writes HTML to a string. It requires the System.Web.UI namespace.

HtmlTextWriter writes HTML programmatically.

It allows you to generate a list of HTML elements, such as <div> elements. You could use StringBuilder to create the HTML, but HtmlTextWriter is sometimes better. Fewer errors are likely.

Example. First, the HtmlTextWriter class is found in the System.Web.UI namespace. If you are not already using ASP.NET, you will need to reference the System.Web assembly. You also need the System.IO namespace for StringWriter.

Tip: HTML is a string. It is easy to generate HTML using StringBuilder, just like any other string.

However: That method can result in complex syntax. We use the HtmlTextWriter class to alleviate these problems.

C# program that uses HtmlTextWriter

using System;
using System.IO;
using System.Web.UI;

class Program
{
    static string[] _words = { "Sam", "Dot", "Perls" };

    static string GetDivElements()
    {
	// Initialize StringWriter instance.
	StringWriter stringWriter = new StringWriter();

	// Put HtmlTextWriter in using block because it needs to call Dispose.
	using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
	{
	    // Loop over some strings.
	    foreach (var word in _words)
	    {
		// Some strings for the attributes.
		string classValue = "ClassName";
		string urlValue = "";
		string imageValue = "image.jpg";

		// The important part:
		writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
		writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1

		writer.AddAttribute(HtmlTextWriterAttribute.Href, urlValue);
		writer.RenderBeginTag(HtmlTextWriterTag.A); // Begin #2

		writer.AddAttribute(HtmlTextWriterAttribute.Src, imageValue);
		writer.AddAttribute(HtmlTextWriterAttribute.Width, "60");
		writer.AddAttribute(HtmlTextWriterAttribute.Height, "60");
		writer.AddAttribute(HtmlTextWriterAttribute.Alt, "");

		writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
		writer.RenderEndTag(); // End #3

		writer.Write(word);

		writer.RenderEndTag(); // End #2
		writer.RenderEndTag(); // End #1
	    }
	}
	// Return the result.
	return stringWriter.ToString();
    }

    static void Main()
    {
	// Demonstrate HtmlTextWriter.
	Console.WriteLine(GetDivElements());
    }
}

Output

<div class="ClassName">
	<a href="">
	<img src="image.jpg" width="60" height="60" alt="" />Sam</a>
</div><div class="ClassName">
	<a href="">
	<img src="image.jpg" width="60" height="60" alt="" />Dot</a>
</div><div class="ClassName">
	<a href="">
	<img src="image.jpg" width="60" height="60" alt="" />Perls</a>
</div>

The new StringWriter is required for the HtmlTextWriter to write to. It is a buffer and everything that is written is written to this. The using-keyword ensures that the system will Dispose of the objects properly.

StringWriter

Foreach-loop. Your program will have a collection of objects it needs to write out, or read from a database. We use a foreach-loop. The example loops through a string array and then uses those strings as the HTML text links.

Foreach

Tags. We need to use "RenderBegin" and "RenderEnd" methods on the HtmlTextWriter. You may recognize the Push and Pop methods on queues. Call RenderBeginTag to open a new level in the HTML with that tag.

And: You must manually close that level of that markup with RenderEndTag. These two methods must be called in pairs.

Tip: Please look at "the important part" in the code above to follow this description.

The example adds an attribute. Attributes in HTML are similar are used with = and quotes. Add the attribute with AddAttribute before BeginRenderTag. Look at the parts of the code that read "HtmlTextWriterAttribute.Class" and similar.

Note: These are enumerations on the specified class. You do not type the tag names in strings. That would result in typos.

Tags overview. Every tag is started and then closed later. This is the most important part. Finally, the Write method is an instance method that writes text in between the tags in HTML.

Tab string. In the constructor to the HtmlTextWriter, use an empty string as the tab string. This will eliminate a lot of whitespace. I was able to reduce the size of my pages by a small percentage this way.

Empty Strings

Fragment that uses string.Empty: C#

using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter,
    string.Empty))
{
    // Insert code here.
}

XmlWriter. Using XmlWriter is very similar to the code shown here, but the output is XML. This is useful for interoperability and settings files. HtmlTextWriter is mainly useful for web pages in ASP.NET.

XmlWriter

Summary. We used the HtmlTextWriter class in the System.Web namespace using the C# language. Use HtmlTextWriter to write HTML instead of StringBuilder alone for the cleanest and object-oriented code.

Note: I am not aware of any performance issues. And the markup is always nicely indented.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf