我有一个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);
}
}
Web表单//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);
是的,您可以在第一个控件中引发事件,在父控件中拾取它,然后让父控件调用第二个控件中的方法/函数。示例(在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
这将在控件加载时引发一个名为datachchange的事件。或者,您可以在响应控件中的另一个事件时引发它(比如按钮被按下时)。这将引发一个父类可以订阅的事件,如下所示(假设页面上有一个名为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()