需要特別注意的是:
添加控件和給控件加事件時絕對不能放到 if(!IsPostback){}裡面,那樣的話,點擊一次後控件會消失,而且事件也不會執行。
protected void Page_Load(object sender, EventArgs e)
{
//將輸入字符串分析為System.Web.UI.Control對象,b為傳進去的值
Control c = ParseControl("<ASP:Button Text = '按我' ID = 'myButton' commandargument = 'b' runat = 'server' />");
//將控件添加大Panel中
this.Panel1.Controls.Add(c);
//查找頁面名為myButton的控件
Button Button = (Button)Page.FindControl("myButton");
//添加事件On_Button
Button.Command += new CommandEventHandler(this.On_Button);
}
//CommandEventArgs為command事件提供數據
protected void On_Button(Object sender,CommandEventArgs e)
{
Response.Write("<script language = 'Javascript' type = 'text/Javascript'>alert('" + e.CommandArgument.ToString() + "');</script>");
}
動態添加控件並添加事件
private void Page_Load(object sender, System.EventArgs e)
{
Button Button1 = new Button();
Button1.CommandArgument = "b1";
Button1.Text = "Btn1";
Button1.Command += new CommandEventHandler(this.OnButton);
PlaceHolder1.Controls.Add(Button1);
Button Button2 = new Button();
Button2.CommandArgument = "b2";
Button2.Text = "Btn2";
Button2.Command += new CommandEventHandler(this.OnButton);
PlaceHolder1.Controls.Add(Button2);
Control c3 = ParseControl("<ASP:Button id='Button3' text='Btn3' commandname='Btn' commandargument='b3' runat='server' />"); //將字符串轉換成web控件
Control c4 = ParseControl("<ASP:Button id='Button4' text='Btn4' commandname='Btn' commandargument='b4' runat='server' />");
PlaceHolder1.Controls.Add(c3);
PlaceHolder1.Controls.Add(c4);
Button myBut = (Button)Page.FindControl("Button3");
myBut.Command += new CommandEventHandler(this.OnButton);
Button myBut2 = (Button)Page.FindControl("Button4");
myBut2.Command += new CommandEventHandler(this.OnButton);
}
public void OnButton(Object Sender, CommandEventArgs e)
{
switch (e.CommandArgument.ToString().ToLower())
{
case "b1":
Label1.Text = "Button 1";
break;
case "b2":
Label1.Text = "Button 2";
break;
case "b3":
Label1.Text = "Button 3";
break;
case "b4":
Label1.Text = "Button 4";
break;
};
}