How to add css style/class to a HtmlTextWriterTag.Td dynamically in .net?

5.9k Views Asked by At

I have the following c# code in my control's RenderContents method. How can I add the style/class that is in external css file?

output.AddAttribute(HtmlTextWriterAttribute.Border, "0");
output.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
output.RenderBeginTag(HtmlTextWriterTag.Table);
output.RenderBeginTag(HtmlTextWriterTag.Tbody);
output.RenderBeginTag(HtmlTextWriterTag.Tr);
//Here -> Need to add some style from external stylesheet.css file
output.RenderBeginTag(HtmlTextWriterTag.Td);
rblLoadSelection.RenderControl(output);
output.RenderEndTag(); //Td
output.RenderEndTag(); //Tr
output.RenderEndTag(); //Tbody
output.RenderEndTag(); //Table
2

There are 2 best solutions below

2
On

You shouldn't reference an external stylesheet between a td and tr. The best place to put it is in the head tag of your document.

Based on your comments, if you just need to add a class to td, do this:

output.AddAttribute(HtmlTextWriterAttribute.Class, "myclass");
1
On

I dont think you can include external CSS (without including it in head and use classes) or do it inline like this:

output.AddStyleAttribute(HtmlTextWriterStyle.Color, "#000000");
output.RenderBeginTag(HtmlTextWriterTag.Td);