因为点击B按钮后会回传,Page_Load又执行一次,btn2当然不见了,如果你确实要用这种方法实现这功能的话,可以在页面加一个HiddenField,然后按下面这样写:
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "A";
btn.Text = "A";
btn.Click += new System.EventHandler(btn_click);
this.form1.Controls.Add(btn);
if (HiddenField1.Value=="1")
{
Button btn2 = new Button();
btn2.ID = "B";
btn2.Text = "B";
btn2.Click += new System.EventHandler(btn2_click);
this.form1.Controls.Add(btn2);
}
}
private void btn_click(object sender, System.EventArgs e)
{
Button b1 = (Button)sender;
Button btn2 = new Button();
btn2.ID = "B";
btn2.Text = "B";
btn2.Click += new System.EventHandler(btn2_click);
this.form1.Controls.Add(btn2);
HiddenField1.Value = "1"; // 主要用来标记已经添加了按钮B
}
private void btn2_click(object sender, System.EventArgs e)
{
Button b2 = (Button)sender;
Button btn3 = new Button();
btn3.ID = "C";
btn3.Text = "C";
this.form1.Controls.Add(btn3);
}