
112
|
Chapter 5: ASP.NET Server Controls
This is the Title of the Book, eMatter Edition
Copyright © 2008 O’Reilly & Associates, Inc. All rights reserved.
When declaring control instances in a code-behind class, it’s a good
idea to use the Protected keyword to ensure that the instance is
available only to the class itself and to any class (such as the .aspx
page) that inherits from it.
An alternate technique in Visual Basic .NET uses the AddHandler statement to
specify a control event along with the address of the procedure that should be
invoked when that event occurs:
Sub Page_Load( )
Protected MyButton As New Button( )
AddHandler MyButton.Click, AddressOf MyButton_Click
End Sub
Sub MyButton_Click(sender As Object, e As EventArgs)
'Event handling code
End Sub
A corresponding RemoveHandler statement also allows you to stop handling a
particular event. The advantage of this technique is that you can stop and start
handling a particular event dynamically. In C#, the
+= operator is used to assign
an event handler to an event:
void Page_Load( )
{
Button MyButton = new Button( );
MyButton.Click += new EventHandler(this.MyButton_Click);
}
void MyButton_Click(Object sender, EventArgs e)
{
// Event handling code
}
As with Visual Basic’s AddHandler keyword, the += operator has a corresponding
-= operator that allows you to unwire an event from its handler dynamically.
Modifying Control Appearance
One of the great