ITPub博客

首页 > 应用开发 > IT综合 > asp.net控件代码

asp.net控件代码

原创 IT综合 作者:qcyhzwq001 时间:2015-04-01 09:06:31 0 删除 编辑
 假定用户控件(UserControl.ascx)中包含按钮控件AButton,希望实现按AButton按钮时,包含该用户控件的页面可以接收到事件。

        UserControl.ascx.cs中的处理:
        1. 定义public的事件委托,如ClickEventHandler;
        2. 在UserControl类中声明事件,如Click;
        3. 在UserControl类中定义引发事件的方法,如OnClick()方法;
        4. 在UserControl类的相关方法中调用引发事件的方法,如在Button_Click()中调用OnClick()。

        public delegate void ClickEventHandler(object sender, EventArgs e);
        public class MyUserControl : System.Web.UI.UserControl
        {
           protected System.Web.UI.WebControls.Button AButton;
           public event ClickEventHandler Click;
           protected void OnClick(EventArgs e) 
           {
               if (Click!=null) Click(this, e); 
           }
           private void AButton_Click(object sender, System.EventArgs e)
           {
               this.OnClick(e);
           }
        }

 
包含UserControl的页面cs文件中的处理:

     1. InitializeComponent()中增加事件处理程序,采用FindControl方法找到UserControl;
     2. 定义事件处理方法,在该方法中处理UserControl的事件,如UserControl_Clicked()。

     private void InitializeComponent()
     {    
           this.Load += new System.EventHandler(this.Page_Load);
           MyUserControl uc = this.FindControl("myUserControlID") as MyUserControl;
           uc.Click += new ClickEventHandler(this.UserControl_Clicked);
     }
     private void UserControl_Clicked(object sender, System.EventArgs e)
     {
           //codego.net  UserControl_Clicked event hanlder
     }

以上就是自定义控件代码举例

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30011186/viewspace-1480996/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: fcntl函数
请登录后发表评论 登录
全部评论

注册时间:2014-11-06

  • 博文量
    7
  • 访问量
    10644