【问题标题】:why i can't add event handlers for events of my usercontrol though page markup为什么我不能通过页面标记为我的用户控件的事件添加事件处理程序
【发布时间】:2012-02-20 18:50:51
【问题描述】:

我有一个具有公共事件的用户控件。当我在我的网页中使用此用户控件并通过页面标记在我的代码中将事件设置为事件处理程序时,我的用户控件的事件不会被设置并且即使在第一页加载时也始终为空。这是我的用户控件的一部分,其中有一个详细信息视图,我正在尝试为其设置事件:

[Serializable(), PersistChildren(false)]
public partial class UserControl_UCDetailsView : System.Web.UI.UserControl
{
    //here is an event for exposing detailsview1 event to the outside code
    public event DetailsViewUpdateEventHandler OnItemUpdating;
    protected void detailsview1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        //here i want it not to be null but it is. by using break points i found out 
        //this is always null and never actually get set while i've set it in markup!
        if (this.OnItemUpdating != null)
            this.OnItemUpdating(sender, e);
    }
}

这是我的 usercontrol 标记的一部分:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UCDetailsView.ascx.cs"
    Inherits="UserControl_UCDetailsView" %>
<asp:DetailsView ID="detailsview1" runat="server" OnItemUpdating="detailsview1_ItemUpdating">
</asp:DetailsView>

这就是我在页面标记中设置事件的方式:

<UC:DetailsView ID="ucDetails" runat="server" OnItemUpdating="ucDetails_ItemUpdating">
</UC:DetailsView>

在 ucDetails_ItemUpdaing 我有一个真正的更新逻辑,比如设置字段等。 那么,如果我在页面加载时设置事件,为什么问题解决了?我错过了什么?也许是一个属性?

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ucDetails.OnItemUpdating += new DetailsViewUpdateEventHandler(ucDetails_ItemUpdating);
    }
}

【问题讨论】:

    标签: c# asp.net events user-controls


    【解决方案1】:

    将 Add 和 Remove 公开为公共属性。

    注意:I've just seen this answer on SO

    public event DetailsViewUpdateEventHandler ItemUpdating; 
    
    public event DetailsViewUpdateEventHandler OnItemUpdating
    { 
       add { this.ItemUpdating += value;} 
       remove { this.ItemUpdating -= value;} 
    } 
    

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 2021-05-16
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      相关资源
      最近更新 更多