views:

299

answers:

3

Hi,

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?

A: 

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

BigBlondeViking
So I need to create a delegate for the UserChange event?
balint
Look at Jon's Post, he has some great code snippets... I think he is showing what I was suggesting. GL
BigBlondeViking
+2  A: 

Hi,

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.

Dmitry Estenkov
+1  A: 

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
}
Jon