動的コントロールでいくつかのテストを行っています。ここにコード:
ASPXページ
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0">Nothing</asp:ListItem>
<asp:ListItem Value="1">Two buttons</asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
コードビハインド:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["CreateDynamicButton"] != null)
{
CreateControls();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
CreateControls();
}
void Button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
Response.Write("You clicked the button with ID " + b.ID);
}
private void CreateControls()
{
if (DropDownList1.SelectedValue.Equals("1"))
{
Panel1.Controls.Clear();
Button b1 = new Button();
b1.ID = "b1";
b1.Text = "Button 1";
Button b2 = new Button();
b2.ID = "b2";
b2.Text = "Button 2";
b1.Click += new EventHandler(Button_Click);
b2.Click += new EventHandler(Button_Click);
Panel1.Controls.Add(b1);
Panel1.Controls.Add(b2);
ViewState["CreateDynamicButton"] = true;
}
}
}
このコードは機能しますが、ご覧Panel1.Controls
のとおり、ボタンを追加する前にすべてのコントロールを削除します。これは、2 回目の作成を選択したときに、重複したコントロール ID の例外が発生するためです。
2 つのボタンの場合、操作は非常に高速であると思いますが、コントロールの数が増えると、精緻化の時間が長くなります。この回避策を使用せずに PostBack 後にコントロールを再生成するより良い方法を教えてください。