为自定义控件添加页面响应事件

ascx:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
ascx.cs:
(1)
public delegate void PostBackDelegate();  //定义委托类型
public event PostBackDelegate PostBackEvent;  //定义委托对象
protected void Button1_Click(object sender, EventArgs e)
{
    if (this.PostBackEvent != null) this.PostBackEvent();  //无参数
}
(2)
public event EventHandler PostBackHandler;
protected void Button1_Click(object sender, EventArgs e)
{
    if (this.PostBackHandler != null) this.PostBackHandler(sender, e);  //有参数
}
aspx.cs:
在Page_Load里(不是!IsPostBack里)加入:
(1)
MyUserControl1.PostBackEvent += new Test_MyFilePath_MyUserControl.PostBackDelegate(MyFuncName);  //new自动生成
protected void MyFuncName()
{
    Response.Write("OOKK");
}
(2)
MyUserControl1.PostBackHandler += new EventHandler(MyFuncName);
protected void MyFuncName(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    btn.Text = "控件按钮名称";  //改变控件按钮名称
    Response.Write("ookk");
}

你可能感兴趣的:(自定义控件)