简体   繁体   English

在动态创建的控件中的文本之间添加BR

[英]add BR between text in dynamically created control

I've got a dynamically created List in asp.net with the following code: 我在asp.net中使用以下代码动态创建了一个List:

HtmlGenericControl li = new HtmlGenericControl("li");
li.ID = "liQuestions" + recordcount.ToString();
li.Attributes.Add("role", "Presentation");
ULRouting.Controls.Add(li);

HtmlGenericControl anchor = new HtmlGenericControl("a");
li.Attributes.Add("myCustomIDAtribute", recordcount.ToString());
anchor.InnerText = "Test " + new HtmlGenericControl("br") + "12345";
li.Controls.Add(anchor);

I tried to put in a HtmlGenericControl but that doesn't work. 我试图放入HtmlGenericControl,但这不起作用。 How do I add a br inbetween Test and 12345 please? 如何在Test和12345之间添加br?

You need to use InnerHtml property 您需要使用InnerHtml属性

HtmlGenericControl li = new HtmlGenericControl("li");
li.ID = "liQuestions" + recordcount.ToString();
li.Attributes.Add("role", "Presentation");
ULRouting.Controls.Add(li);

HtmlGenericControl anchor = new HtmlGenericControl("a");
li.Attributes.Add("myCustomIDAtribute", recordcount.ToString());
anchor.InnerHtml = "Test <br/> 12345";
li.Controls.Add(anchor);

Or, like this: 或者像这样:

anchor.Controls.Add(new LiteralControl("Test")); //or new Literal("Test");
anchor.Controls.Add(new HtmlGenericControl("br"));
anchor.Controls.Add(new LiteralControl("12345")); //or new Literal("12345");

Although I'm not able to test it myself right now, I believe the first method in hazzik's answer would work, but I don't think his second method would. 尽管我现在无法自己进行测试,但我相信hazzik答案中的第一种方法会起作用,但是我认为他的第二种方法不会起作用。 The HtmlGenericControl is known to not support self-closing elements, which the BR element is. 众所周知,HtmlGenericControl不支持BR元素那样的自动关闭元素。

The following SO questions have more detail and another possible solution: 以下SO问题具有更多详细信息和另一种可能的解决方案:

HtmlGenericControl("br") rendering twice HtmlGenericControl(“ br”)渲染两次

Server control behaving oddly 服务器控制行为异常

Adding <br/> dynamically between controls asp.net 在控件ASP.NET之间动态添加<br/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM