何时附加自定义事件处理程序?

时间:2008-11-20 05:09:10

标签: asp.net event-handling

我在GridView中有一个UserControl。 何时将自定义事件处理程序附加到UserControl? 请告诉我,因为我不知道。

在下面的场景中,UserCreated事件处理程序在触发UserCreated事件时为null,即在DataBinding期间。页面完全加载后,事件处理程序可用。

用户控件

    public event EventHandler UserCreated;
    public event EventHandler UserSelected;

     /// 
    /// Bubble up the  UserCreated event
    /// 
    protected virtual void OnUserCreated(object sender, UserCreatedArgs e)
    {
        EventHandler handler = UserCreated;
       /* 
            UserCreated above is null during databinding. No handler is present
            A handler is present after page has fully loaded i.e. UserCreated != null
        */

        if (handler != null)
        {
            handler(this, e);
        }
    }

    /// 
    /// Raise the OnDataBindingEvent
    /// 
    protected override void OnDataBinding(EventArgs e)
    {            
        base.OnDataBinding(e);
        InitialiseControl();
    }

    /// 
    /// Initialises the data in the UserControl.
    /// 
    private void InitialiseControl()
    {           
       List userList =
            UserController.GenerateUserNameDropDownList(UserGroupName);
       OnUserCreated(userList);
    }

托管哪个UserControl的页面

   /// 
    /// Handles the Load event of the Page control.
    /// 
    protected void Page_Load(object sender, EventArgs e)
    {
         UserCreatedHandler += UserControl.UserCreated
    }

    protected void UserCreatedHandler(object sender, UserControl.UserCreatedArgs e)
    {
          ...handle userCreated event
    }

页面标记

asp:GridView ID =“keyPersonnelGridView”runat =“server”   列     ASP:模板列      ItemTemplate中       userControl:UserName ID =“personnelList”runat =“server”UserGroupName =“All Users”     / ItemTemplate中    / ASP:模板列    标签的关闭  / ASP:GridView的

任何善意的人都可以解释为什么在事件被解雇时我的事件处理程序不存在吗?

1 个答案:

答案 0 :(得分:1)

你需要翻转它

UserCreatedHandler += UserControl.UserCreated

成为

UserControl.UserCreated += new EventHandler(UserCreatedHandler); 

目前,“UserCreatedHandler”具有UserCreated事件的错误签名。声明UserCreated事件时,应使用通用EventHandler:

public event EventHandler<UserCreatedArgs> UserCreated;