代码之家  ›  专栏  ›  技术社区  ›  Jimmy

ASP.NET用户控件事件传播问题

  •  3
  • Jimmy  · 技术社区  · 16 年前

    我有一个简单的用户控件,其中包含一些触发事件的按钮,我希望使用该控件的页面能够处理这些事件。我的代码设置如下:

    public event EventHandler Cancel;
    public event EventHandler Confirm;
    public void Confirm_Click(object sender, EventArgs e)
    {
        if (Confirm != null)
            Confirm(this, e);
    }
    public void Cancel_Click(object sender, EventArgs e)
    {
        if (Cancel != null) 
            Cancel(this, e);
    }
    

    但是当我试图从使用控件的页面加载事件的页面调用这些时,我没有任何自定义事件

    ASPX码

    <%@ Register TagPrefix="btg" TagName="CustomControl" Src="~/Search/CustomControl.ascx" %>
    <btg:CustomControl ID="btgControl" runat="server" ></btg:CustomControl>
    

    这可能是因为用户控件中的按钮在更新面板中吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Joseph Yaduvanshi    16 年前

    你不应该看到方法。你应该去看活动。

    在父页的加载中,需要执行以下操作:

    myUserControl.Cancel += new EventHandler(myUserControl_Cancel);
    

    您可以点击选项卡,选项卡来自动生成方法存根。看起来像:

    void myUserControl_Cancel(object sender, EventArgs e) {}
    

    然后,此代码将在用户控件的方法中调用后激发。为了激活该代码,必须将事件分配给用户控件上的按钮事件。

    edit:myUserControl是用户控件的ID。还有一些人认为事件处理程序应该在页面的init方法中。

    编辑:

    页面中是否正确引用了您的用户控件?例如,您是在web.config中注册用户控件还是使用页面中的引用指令?

    另外,你有没有尝试过清理和重建解决方案?如果用户控件是动态创建/加载的,则必须在与实例化控件相同的范围内连接事件。为了动态加载用户控件,必须在页面中有一个占位符,并执行以下操作:

    UserControl control = Page.LoadControl("~/ControlPath/ControlName.ascx");
    ((MyUserControlClass)control).Cancel += += new EventHandler(myUserControl_Cancel); // etc...
    
    推荐文章