Generating HTML in C#

I have some C# code which looks something like this:
using (StreamWriter output = new StreamWriter(filename)
{
    output.Write("<HTML>");
    output.Write("<HEAD>...</HEAD>");
    output.Write("<BODY>");
    output.Write("<TABLE>");
    output.Write( table header stuff);

    // Now we output the HTML Table rows of data
    foreach(MyData data in myDataList)
    {
        output.Write("<tr><td>" + data.column1 + "</td><td>" + data.column2 + "</td><td>" + data.column3 + "</td></tr>");
    }

    output.Write("</TABLE>");
    output.Write("</BODY>");
    output.Write("</HTML>");
}

Open in new window

My question is, is there a better way of doing this? Can I somehow create a template, which looks like an HTML file, something like:
template = 
<HTML>
  <HEAD>
    ...
  </HEAD>
  <BODY>
    <TABLE>
      <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
      {magically fill in rows here from data}
    </TABLE>
  </BODY>
</HTML>

Open in new window

This looks nice, all except how would I get my C# code to "magically fill in rows here from data"?
deleydAsked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi deleyd;

Microsoft has developed a templating framework called T4 which they use to create class files and windows form templates as well as many others. This is also available to developers please see the links below.
Code Generation and T4 Text Templates
Run-Time Text Generation with T4 Text Templates
Writing a T4 Text Template
0
 
Dustin SaundersConnect With a Mentor Director of OperationsCommented:
You can use
string.Format(str1, arg1, arg2, ...)

Open in new window

to do that and keep the HTML easy to edit.  I put this together real quick as an example :

public string GetHTML(DataTable table)
{
	string template = @"
	<HTML>
	  <HEAD>
		...
	  </HEAD>
	  <BODY>
		<TABLE>
		  {0}
		  {1}
		</TABLE>
	  </BODY>
	</HTML>";
	
	return string.Format(template, GetColumns(table), GetRows(table));
}

public string GetColumns(DataTable table)
{
	string thead = @"
			<thead>
				<tr>
					{0}
				<tr>
			</thead>";
		
	string html = string.Empty;	
	
	foreach (DataColumn c in table.Columns)
	{
		html += "<td>" + c.ColumnName + "</td>\n";
	}
	
	return string.Format(thead, html);
}

public string GetRows(DataTable table)
{
	string tbody = @"
			<tbody>
				{0}
			</tbody>";
			
	string html = string.Empty;
	
	foreach (DataRow row in table.Rows)
	{
		html += "<tr>"
		for (int i = 0; i < table.Columns.Count; i++)
		{
			html += "<td>" + row[i].ToString() + "</td>";
		}
		html += "</tr>\n";
	}
	
	return string.Format(tbody, html);
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.