Thursday, March 3, 2011

Custom Event Handler

How to propogate any event for the control in the master page to all the child pages?
This can be achieved by Event Handling in .NET:
1. Create an event class that inherits the EventArgs class.
2. Create a Delegate for handling the event.
3. Declare an event in the master page.
4. Add the event to any of the method which raises the event.

Add the following Event Class in the APP Code folder in the website:
Event Class:
public class ABCCodeChangeEventArgs: EventArgs
{
                public ABCCodeChangeEventArgs(string toCode)
                {
                                _toCode = toCode;
                }
                private string _toCode;
                public string Code
                {
                                get { return _toCode;}
                                set{_toCode=value}
                }
}

public delegate void ABCCodeChangeEventHandler(object sender, ABCCodeChangeEventArgs e);

-------------------------------------------------------------------------------------------------------------
MasterPage.CS
Add the event to any control in the Master page:
public event ABCCodeChangeEventHandler BubbleABCCodeChangedEvent;
protected void ddlDropDown_SelectedIndexChanged(object Sender, EventArgs e)
{
                ABCCodeChangeEventArgs eventArgs = new
                ABCCodeChangeEventArgs(ddlDropdown.SelectedValue);
                BubbleABCCodeChangedEvent(this, eventArgs);
}
Add the following code in other pages in the project:
Page Load Event:
Master.BubbleABCCodeChangedEvent +=new ABCCodeChangeEventHandler(Master_BubbleABCCodeChangedEvent);
Define the method in the page:
void Master_BubbleABCCodeChangedEvent(object sender, ABCCodeChangeEventArgs e)
{
}

No comments:

Post a Comment