1

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

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

用户控制

    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:TemplateField ItemTemplate userControl:UserName ID="personnelList" runat="server" UserGroupName="All Users" /ItemTemplate /asp:TemplateField ..其余标签关闭 / asp:网格视图

任何善良的灵魂都可以解释为什么在事件触发时我的事件处理程序不存在吗?

4

1 回答 1

1

你需要翻转它

UserCreatedHandler += UserControl.UserCreated

变成

UserControl.UserCreated += new EventHandler(UserCreatedHandler); 

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

public event EventHandler<UserCreatedArgs> UserCreated;
于 2009-03-01T04:24:54.603 回答