プレースホルダーで動的に生成されたラベル間に改行を作成する方法は?
-
06-07-2019 - |
質問
これは、ファイルの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);
生成された各コントロール間に改行が必要です。
解決
Line Breakの問題の解決策は以下のとおりです。ただし、Page_Loadイベントでこれを行うと、イベントハンドラーが機能せず、Page Life Cycleの問題が発生します。基本的に、イベントハンドラーを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);
他のヒント
別の解決策は、各コントロールをパネルに追加して、それぞれを<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);
方法:ASP.NET Webページにプログラムでコントロールを追加する
場合によっては、 静的テキストとコントロールの両方を作成します。 静的テキストを作成するには、リテラルWebサーバーまたはラベルWebサーバーを使用できます コントロール。その後、これらを追加できます あなたがするようにコンテナへのコントロール その他のコントロール。詳細については 作成されたコントロールのビューステートについて 実行時に、動的Webサーバーを参照してください コントロールとビューステート。
所属していません StackOverflow