动态添加控件的事件,语句:
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Control.Command += new CommandEventHandler(this.EventFun);
具体的代码请看下面:
需要特别注意的是:
添加控件和给控件加事件时绝对不能放到 if(!IsPostback){}里面,那样的话,点击一次后控件会消失,而且事件也不
会执行。
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
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>");
}