C# 以编程方式添加 span 标记,而不是 Label 控件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1799158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:57:29  来源:igfitidea点击:

Programmatically add a span tag, not a Label control?

c#asp.nethtmlcode-behind

提问by Hcabnettek

How can I add a spantag 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.

如何span从后面的代码添加标签?是否有等效的 HtmlControl?我目前正在这样做。我正在 Itemplate 实现中将行构建到表中。

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 LiteralControlthis way? Does anyone have any better ideas of how to do this?

我知道我可以使用new Label(),但我试图避免在这里使用服务器控制。我使用LiteralControl这种方式是否正确?有没有人对如何做到这一点有更好的想法?

采纳答案by Canavar

With HtmlGenericControl you can create a span dynamically like that :

使用 HtmlGenericControl,您可以像这样动态创建跨度:

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

回答by Frank Schwieterman

new HtmlGenericControl("span")

回答by Oakcool

Following the idea that our friend Canavar said.

遵循我们的朋友 Canavar 所说的想法。

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.

在 System.Web.UI.HtmlControls 命名空间下查看,您将看到一大堆已映射到对象的 HTML 控件(如果您可以使用这些控件)。HtmlGenericControl 适用于任何未在 .NET 中定义的控件,SPAN 就是一个例子。

Happy Coding.

快乐编码。

回答by birdus

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);

回答by Kursat Turkay

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

使用文字控制。你可以添加任何你想要的 html 内容。我不推荐标签。(有关更多信息,请搜索 -label 与文字 -。)

回答by Licht

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

我知道我迟到了,但我想为这个问题提供我的解决方案。

public class HtmlSpan: HtmlGenericControl
{
  public HtmlSpan(): base("span") { }
}