【问题标题】:How to create line breaks between dynamically generated labels in a placeholder?如何在占位符中动态生成的标签之间创建换行符?
【发布时间】:2010-10-24 05:42:38
【问题描述】:
这是文件Page_Load 事件代码后面的代码:
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);
我想在生成的每个控件之间换行。
【问题讨论】:
标签:
asp.net
dynamic
button
line-breaks
placeholder
【解决方案1】:
但是,如果您在 Page_Load 事件中执行此操作,则您的换行问题的解决方案如下,那么您的事件处理程序将无法工作并且您将遇到页面生命周期问题。基本上,为了让您的事件处理程序在 PostBack 上触发,您确实需要在页面生命周期的早期创建这些动态控件。如果遇到此问题,请尝试将代码移至 OnInit 方法。
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
//Add This
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);
【解决方案2】:
另一个解决方案是您可以将每个控件添加到面板中,这会将它们各自呈现在 <div> 中,从而产生您正在寻找的效果。
对我来说,这将更加动态,因为如果您隐藏任何控件,div 将折叠并且不会留下空行。
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
//Add control to a panel, add panel to placeholder
Panel lbPan = new Panel();
lbPan.Controls.Add(linkButton);
PlaceHolder1.Controls.Add(lbPan);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
//Add control to a panel, add panel to placeholder
Panel lblPan = new Panel();
lblPan.Controls.Add(label);
PlaceHolder1.Controls.Add(lblPan);