Programmatically add a span tag, not a Label control?
Asked Answered
S

6

37

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?

Sonya answered 25/11, 2009 at 18:51 Comment(0)
G
79

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);
Galcha answered 25/11, 2009 at 18:56 Comment(0)
K
4
Label span = new Label();
span.Text = "From<br/>Date";
span.CssClass = "nonExpense";
headerCell.Controls.Add(span);

Or, alternatively:

Label span = new Label {Text = "From<br/>Date", CssClass = "nonExpense"};
headerCell.Controls.Add(span);
Keslie answered 6/1, 2012 at 19:1 Comment(1)
Isn't this going to create a label tag?Dugger
L
2
new HtmlGenericControl("span")
Limiting answered 25/11, 2009 at 18:53 Comment(0)
O
1

Following the idea that our friend Canavar said.

Look under System.Web.UI.HtmlControls namespace and you will see a whole bunch of HTML controls that have been mapped to objects, if you can use those. HtmlGenericControl fits in to any controls that are not defined in .NET and SPAN is a exemple of that.

Happy Coding.

Olympus answered 25/11, 2009 at 19:32 Comment(0)
Y
1

I know I'm late but I wanted to provide my solution for this issue.

public class HtmlSpan: HtmlGenericControl
{
  public HtmlSpan(): base("span") { }
}
Ye answered 11/2, 2016 at 18:53 Comment(0)
R
0

use literalcontrol. you can add whatever html content you want. I dont recommend label. (for more information search -label vs literal-.)

Radioman answered 8/3, 2013 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.