asp.net: send an object's event from a UserControl to its Parent

送分小仙女□ 提交于 2019-12-14 02:22:00

问题


I have a User class with functions to Login() and Logout() and GetData(). There's a UserChanged event, it fires when either of these functions are called.

I have UserControls on my Default.aspx (they're added dynamically).

I have a UserControl named Login.ascx. It provides the functionality to use the User class: you can Login / Logout here. I have an ****EventHandler* for **UserChanged***** (if I don't have one, it will fail with a object not found exception).

I need to alert the other UserControls about the changes to the user's state. I somehow need to pass the UserChanged event from Login.ascx to its Parent, Default.aspx.

How can I do this?


回答1:


Login.ascx.cs

public delegate void OnUserChangedHandler(object sender);
public OnUserChangedHandler OnUserChanged;

private void RaiseUserChangedEvent() //Call this method when the user changes
{
    //UserChanged Event
    if (OnUserChanged != null)
    {
        OnUserChanged(this);
    }
}

Default.aspx.cs

protected override void OnInit(EventArgs e)
{
    InitializeComponent();
    base.OnInit(e);
}

private void InitializeComponent()
{
    loginControl.OnUserChanged += OnUserChanged;
}

private void OnUserChanged(object sender)
{
    //Code here to do something with other controls on this page
}



回答2:


There is another option to tell parent controls about some actions - RaiseBubbleEvent.

You can read about it here: Using RaiseBubbleEvent to Tell a Parent ASP.NET Control to Rebind

The thing is that child controls calls Method RaiseBubbleEvent(...) And all it's parents (no matter how far are they in hierarchy) can override method OnBubbleEvent to handle this event. return value of that methods indicates whether it's needed to pass this event to the next parent or not.




回答3:


First, the control needs to broadcast the UserChanged Event, and then page needs to be wired up to listen for the event.

There are a lot a good resources out there on how to implement custom events and event handlers...

Try this one from csharphelp.com

http://www.csharphelp.com/archives4/archive603.html



来源:https://stackoverflow.com/questions/1039440/asp-net-send-an-objects-event-from-a-usercontrol-to-its-parent

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