As we've mentioned, ASP.NET server controls expose and raise server events. However, because the server can handle only active events, it's important to understand the difference between active and passive events. Active events include clicking a button or a link, filling out a text box, pressing a key on the keyboard-anything you purposefully click, select, drag, or otherwise interact with. Passive events include moving the mouse to rollover an image or other page object or scrolling down a page.
As events occur, you can choose to have the server process them as they happen or to process them as a collection during a form submission. Keep in mind that "as they happen" sounds attractive, but it is connection and processor heavy. Consider a user entering their personal information in a web form. Each bit of information entered into each text box sends a Post to the server. To demonstrate, let's change our helloWorld web form example to contact the server as soon as the value in the text box changes. To do so, all we need to add is autopostback=true to the tbName text box as shown in Listing 14.3. Preview the page in a web browser. As you can see in the result shown in Figure 14.4, the event triggers the validation and the response as soon as you activate and leave the
tbName text box.
Listing 14.3: HELLOWORLDAUTOPOST-VB.ASPX IN VB.NET
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %> <script runat="server"> Sub tbName_Change(Sender As Object, E As EventArgs) lblWelcome.Text = "Hello " + tbName.Text End Sub </script> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Hello World Form</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <%= "Sample ASP.NET Script Page" %> <form runat="server"> <label>Your Name:</label> <asp:textbox OnTextChanged="tbName_Change" autopostback=true runat="server" TextMode="SingleLine" /> <asp:button runat="server" Text="Enter" /> <asp:label runat="server" > </asp:label> </form> </body> </html>
Figure 14.4: Viewing the output from helloWorldauto- post-VB.aspx in Internet Explorer
Obviously, adding an active Post to each web server control could quickly bring your web form to a crawl and consume a great deal of server resources. That said, in almost every case, you want to handle all events as a collection.
Whether actively or collectively, a server control sends information to the server in two pieces- an object that identifies the server control generating the event and an object that describes any pertinent event information. Typical trigger events are OnClick, OnDataBinding, OnDisposed, OnInit, OnLoad, OnPreRender, and OnUnload. Just as we did in our helloWorld.aspx example, you can take advantage of each of these events by wiring your server control to listen and then react to an event.