ASP.NET How can 2 dynamically loaded user controls respond to each others events?

萝らか妹 提交于 2019-12-11 16:21:20

问题


Greetings All, I have two ascx's loaded in the page-init event of an aspx page. Control 1 has a radio button list that I want a dropdown list on control 2 to respond to it's selectedIndex change. So far I call RaiseBubbleEvent on the SelectedIndexChange handler and I pass on a control reference and commandArgs. Then in the aspx I override OnBubbleEvent and I am able to receive the control reference and commandArgs. My question is how do I pass this information on to Control 2. The page is not aware of the controls as they are loaded dynamically and added to asp:PlaceHolders in the aspx. I need Control 2 to know which radio button was selected so I can change the datasource for the dropdown on control 2. Does anyone have any examples of something like this? Any pointers or tips would be appreciated.

Thanks, ~ck in San Diego


回答1:


Well, Control 2 should really just be attaching to the 'SelectedIndexChanged' event of the other control. Is that not possible for some reason?




回答2:


I'm not sure this is a very good solution but it should work. Create a handler for the event in control 2 and have some way of accessing a delegate to that handler. Then just hookup the event of control 1 to the handler returned by that accessor. Very crude example:

In control1:

public event SelectedIndexChanged;

public void PageLoad()
{
    radioList.SelectedIndexChanged += new EventHandler(RadSelectedIndexChanged);
}

public void RadSelectedIndexChanged(object sender, EventArgs args)
{
    SelectedIndexChanged(sender, args);
}

In aspx page:

control1.SelectedIndexChanged += control2.GetHandler();

In control2:

public EventHandler GetHandler()
{
    return new EventHandler(HandleEvent);
}

protected void HandleEvent(object sender, EventArgs args)
{

}



回答3:


Since you mention that the page is not aware of these controls the best thing is to have the Control1 class to expose an interface with an I-want-to-listen-to-your-event setter method.

Control2 should search its parent (the page) for other sibling control(s) that implement the interface, and then call the setter passing a reference to their handler.

This way the controls can be dropped onto any other page without modification.

Edit:

Added a sample web application for download. The source code is released to the public domain.



来源:https://stackoverflow.com/questions/1309709/asp-net-how-can-2-dynamically-loaded-user-controls-respond-to-each-others-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!