Programmatically add a span tag, not a Label control?

Hcabnettek picture Hcabnettek · Nov 25, 2009 · Viewed 76.2k times · Source

How can I add a span tag from a code behind? Is there an equivalent HtmlControl? I am currently doing it this way. I am building out rows to a table in an Itemplate implementation.

var headerCell = new TableHeaderCell { Width = Unit.Percentage(16)};
var span = new LiteralControl("<span class='nonExpense'>From<br/>Date</span>");
headerCell.Controls.Add(span);
headerRow.Cells.Add(headerCell);

I know I could use new Label(), but I am trying to avoid a server control here. Am I correct in using the LiteralControl this way? Does anyone have any better ideas of how to do this?

Answer

Canavar picture Canavar · Nov 25, 2009

With HtmlGenericControl you can create a span dynamically like that :

var span = new HtmlGenericControl("span");
span.InnerHtml = "From<br/>Date";
span.Attributes["class"] = "nonExpense";
headerCell.Controls.Add(span);