While technically you _can_ use the control's page property, its a bit of a
hack to do so, and isn't really an event handler, all you're
doing is invoking a method on the Page instance. What if your control is
contained within another control, and not a page, and you want
the control to fire the event properly? For that you need to use a delegate
to do the real event handling:
Within your control you can declare:
public delegate void MyButtonClick(object sender, EventArgs e );
then, let's say your control has a button called "btnOK". You want your
control to respond to that OK button click (via postback), but you also
want to be able to notify the control's container (or anything else) that
the OK button was clicked within the control. Do do that you need to
declare an event:
public event MyButtonClick MyButtonClicked;
Now you can fire off that event within your control's btnOK_clicked
handler:
In your Page_Load for your control, you can set up the event handler for
your button:
btnOK.Click += new EventHandler( this.btnOK_Click );
And your btnOK_Click event handler:
private void btnOK_Click(object sender, EventArgs e)
{
if ( MyButtonClicked != null)
// call the event handler in all subscribing controls
MyButtonClicked( sender, e );
}
And finally, in the page you want to respond to the event:
myControl.MyButtonClicked += new MyControl.MyButtonClick(
this.MyButtonClick );
And finally (again), your page's event handler:
public void MyButtonClick( object sender, EventArgs e)
{
Response.Write("You clicked the OK button from within the user control
MyControl!<br>");
}
That should be enough to give you a good idea of rigging up event