ASP.NET用户控件返回事件的方法2008-01-15 14:50:31 来源:编程论坛 作者:
ASP.NET用户控件一般适用于产生相对静态的内容,所以没有builtin的事件支持。本文讨论用户控件返回事件的方法。 ASP.NET用户控件一般适用于产生相对静态的内容,所以没有builtin的事件支持。本文讨论用户控件返回事件的方法。
假定用户控件(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) { // UserControl_Clicked event hanlder }
|
|
||||
|
|
||||
|
|
|
||||
|
|
||||
|
|
|
||||
|
|
||||
|
|