I'm building a HTML table from a C# typed list. So far building the table works fine, but I now need to append a style to one of the <TD>
tags within the string that builds the table.
What I have tried is simply adding the style definition to the TD
when appended to the string using string builder. But I get syntax errors using around the style definition.
Question: How can you append a style definition to tag within a string?
I create the table body using String Builder string instance:
StringBuilder releaseStatusTableBodyData = new StringBuilder();
Then add a row and col to the table string. Removing the double quotes from the style didn't remove the syntax error shown either:
foreach(var row in releaseStatusList)
{
//for each record create a new table row
releaseStatusTableBodyData.Append("<TR>\n");
releaseStatusTableBodyData.Append("<TD style=""bgcolor: green;"">"); //added the style to the TD here, but get syntax error on the style telling me ) is required.
releaseStatusTableBodyData.Append(row.Days_Owned);
releaseStatusTableBodyData.Append("</TD>");
releaseStatusTableBodyData.Append("</TR>\n"); //end of row
}
Put a verbatim literal (@
) at the beginning of your string.
releaseStatusTableBodyData.Append(@"<TD style=""background-color: green;"">");
^^^
From some backgrounds adding escape strings within the string might seem easier, but for me this is much easier to read.
It might also be worth trying an HtmlTextWriter
instead. It's essentially doing the same thing with a little help specific to HTML.
string html;
using (var sw = new StringWriter())
using (var hw = new HtmlTextWriter(sw))
{
hw.RenderBeginTag(HtmlTextWriterTag.Tr);
hw.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "green");
hw.RenderBeginTag(HtmlTextWriterTag.Td);
hw.RenderEndTag();
hw.RenderEndTag();
html = sw.ToString();
}
What's a little odd is that you have to add the style attribute before rendering the Td
tag.
What's good is that you get to work with a lot of predefined constants for tag and style names. And this is a whole lot easier if you need some conditional logic.
hw.RenderBeginTag(HtmlTextWriterTag.Tr);
if(makeThisGreen)
hw.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "green");
if(makeThisBold)
hw.AddStyleAttribute(HtmlTextWriterStyle.FontWeight, "bold");
hw.RenderBeginTag(HtmlTextWriterTag.Td);
hw.RenderEndTag();
hw.RenderEndTag();
With a StringBuilder
when you get to the second condition you'd have to check whether you already started the style
attribute to make sure you didn't create it twice. Then you'd have to check whether either one of those conditions was true so you'd know whether to add the ending quote to the style
attribute. (Or you could create a method to do all that for you.) But that work is already done in the HtmlTextWriter
class.
You can also use WriteBeginTag(string)
and WriteEndTag(string)
which give you more explicit control over writing your tags.