Friday, October 08, 2004

Adding an Event Handler for a Button in a Web Control

//Declare the Event as an object.
private static readonly object EventSave = new object();

//Create a Property to enable the user assign an Event.

[
Category("Action"),
DefaultValue(""),
Description("Raised when the user clicks the Save button")
]
public event EventHandler Save
{
add
{
Events.AddHandler(EventSave,value);
}
remove
{
Events.RemoveHandler(EventSave,value);
}
}

//get the list of events for the handler, if not null wire it to the handler in the button save click event inside the web control.

EventHandler SaveHandler=(EventHandler)Events[EventSave];
if(SaveHandler!=null)
{
SaveHandler(this,e);
}


***********Another example using Event Bubbling********************


# region EventBubbling
protected virtual void onSave(EventArgs e)
{
EventHandler SaveHandler=(EventHandler)Events[EventSave];
if(SaveHandler!=null)
{
SaveHandler(this,e);
}
}
#region Event bubbling
protected override bool OnBubbleEvent(object source, EventArgs e)
{
bool handled = false;
if (e is CommandEventArgs)
{
CommandEventArgs ce = (CommandEventArgs)e;
if (ce.CommandName == "Save")
{
onSave(EventArgs.Empty);
handled = true;
}
}
return handled;
}
#endregion Event bubbling

No comments: