0

我有 1 个 Web 表单和多个用户控件。用户控件之一触发事件。该页面正在侦听并获取控件发出的值。然而,其他用户控制侦听附加到事件,但从未获得该方法。

用户控制 1

public delegate void GetOrgIdEventHandler(long orgId);

public event GetOrgIdEventHandler GetOrgId;

protected void gvSearchResults_SelectedIndexChanged(object sender, EventArgs e)
{
    if (GetOrgId != null)
    {
        GetOrgId(Id);
    }
}

网页表格

//Search1 is the Id of the User Control on the web form - This is working. 
//It calls the method in the assignment
Search1.GetOrgId += 
new SearchGridViewSelectedIndexChangedEventHandler(GetTheOrgId);

用户控制 2

//SearchUserControl is the name of the User Control 2 Class
protected SearchUserControl mySuc = new SearchUserControl();

//The line below works, however the method does not get called. This is where it fails.
//I set a breakpoint in GetTheOrgId but I never get to that break.
mySuc.GetOrgId += new SearchGridViewSelectedIndexChangedEventHandler(GetTheOrgId);
4

1 回答 1

0

是的,您可以在第一个控件中引发事件,在父控件中获取它,然后让父控件在第二个控件中调用方法/函数。示例(在 VB.Net 中):

用户控制一:

部分类 user_controls_myControl 继承 System.Web.UI.UserControl

 Public Event DataChange As EventHandler

 'now raise the event somewhere, for instance when the page loads:

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     RaiseEvent DataChange(Me, New EventArgs)
end sub
  end Class

这将在控件加载时引发一个名为 DataChange 的事件。或者,您可以使用控件引发它以响应另一个事件(例如按下按钮时)。这将引发父级可以订阅的事件,如下所示(假设您在页面上有一个名为 MyControl1 的控件):

主页:

Protected Sub myControl_dataChange(ByVal sender As Object, ByVal e As EventArgs) handles myControl1.DataChange

结束子

现在,您可以在第二个控件中公开一个方法,如下所示:

Partial Class user_controls_myOtherControl
    Inherits System.Web.UI.UserControl

    public sub callMe()
       'do something
    end Sub

end Class

然后,您可以从父页面调用第二个控件中的方法,如下所示:

me.userConrol2.callMe()

如果您仍有疑问,请告诉我。

于 2013-05-28T17:33:53.647 回答