我有1个网络表单和多个用户控件。其中一个用户控件触发事件。页面正在侦听并获取控件发出的值。但是,其他用户控制对事件的监听附加但从未进入该方法。
用户控制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);
答案 0 :(得分:0)
是的,你可以在第一个控件中引发事件,在父控件中拾取事件,然后让父控件在第二个控件中调用方法/函数。示例(在VB.Net中):
用户控制一个:
Partial Class 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
End Sub
现在,您可以在第二个控件中公开一个方法,如下所示:
Partial Class user_controls_myOtherControl
Inherits System.Web.UI.UserControl
public sub callMe()
'do something
end Sub
end Class
然后,您可以从父页面调用第二个控件中的方法,如下所示:
me.userConrol2.callMe()
如果您仍有疑问,请与我联系。