我正在使用动态控件进行一些测试。这里的代码:
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
在添加按钮之前删除了所有控件,因为当我第二次选择创建它们时,我得到了重复控件 ID 的例外。
我认为对于两个按钮,操作非常快,但是如果控件数量较多,则制作时间会更长。您能否建议我在没有此解决方法的情况下在 PostBack 之后重新生成控件的更好方法?