Skip to main content
 首页 » 编程设计

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

2024年02月06日19Renyi-Fan

我在 asp.net 中有一个动态创建的列表,代码如下:

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

我试图放入一个 HtmlGenericControl,但这不起作用。请问如何在 Test 和 12345 之间添加 br?

请您参考如下方法:

您需要使用 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); 

或者,像这样:

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