Reputation: 1832
Im am creating an email using MailMessage
and would like to embed a dynamically populated table. I've set a MailMessage
property to IsBodyHtml
so I've already been able to insert HTML encoded text into the body of the email. Using that I could easily create the top and bottom of the table, but creating the rows seems like a StringBuilder
nightmare.
The table will have 6 columns and a variable number of rows that would be populated from a collection. The requestor would prefer NOT to send the data as an attachment.
Any suggestions on how to best develop a better solution?
Thanks in advance
Upvotes: 2
Views: 2832
Reputation: 32604
It's really not a StringBuilder
nightmare at all.
You can build a class, call it TableBuilder
or whatever you'd like, that will encapsulate this logic.
public class TableBuider
{
private StringBuilder builder = new StringBuilder();
public string[] BodyData { get; set; }
public int BodyRows { get; set; }
public TableBuider(int bodyRows, string[] bodyData)
{
BodyData = bodyData;
BodyRows = bodyRows;
}
/// <summary>
/// Since your table headers are static, and your table body
/// is variable, we don't need to store the headers. Instead
/// we need to know the number of rows and the information
/// that goes in those rows.
/// </summary>
public TableBuider(string[] tableInfo, int bodyRows)
{
BodyData = tableInfo;
BodyRows = bodyRows;
}
public string BuildTable()
{
BuildTableHead();
BuildTableBody();
return builder.ToString();
}
private void BuildTableHead()
{
builder.Append("<table>");
builder.Append("<thead>");
builder.Append("<tr>");
AppendTableHeader("HeaderOne");
AppendTableHeader("HeaderTwo");
builder.Append("</tr>");
builder.Append("</thead>");
}
private void BuildTableBody()
{
builder.Append("<tbody>");
builder.Append("<tr>");
// For every row we need added, append a <td>info</td>
// to the table from the data we have
for (int i = 0; i < BodyRows; i++)
{
AppendTableDefinition(BodyData[i]);
}
builder.Append("</tr>");
builder.Append("</table");
}
private void AppendTableHeader(string input)
{
AppendTag("th", input);
}
private void AppendTableDefinition(string input)
{
AppendTag("td", input);
}
private void AppendTag(string tag, string input)
{
builder.Append("<" + tag + ">");
builder.Append(input);
builder.Append("</" + tag + ">");
}
}
}
The AppendTableHeader
, AppendTableDefinition
, and AppendTag
methods encapsulate all of the tedious parts of the StringBuilder
.
This is just a basic example as well, you can build upon it as well.
Upvotes: 2
Reputation: 11466
This article is Lightswitch specific. But the example code shows how to use XHTML and embedded LINQ expressions to populate a variable row table in an HTML email. I think you should be able to adapt it to suit your application.
Upvotes: 0