Article

Beginning ASP.NET Using VB.NET - Chapter 14: ASP.NET Server Controls

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Next

Events

ASP.NET server controls support the ability to assign event handlers in order to execute programmatic logic in response to whatever events a given ASP.NET server control may raise. As we saw in Chapter 3, an event handler is essentially the code you write to respond to a particular event. For example, a Button control raises an OnClick event after being clicked; a ListBox control raises an OnSelectedIndexChanged event when its list selection changes; a TextBox control raises an OnTextChanged event whenever its text changes, and so on.

Events and event handlers are extremely useful to us as web developers, because they provide a mechanism for responding dynamically to events in our forms, in that we can write our own event handlers to perform any special logic or processing that the form or control calls for. For example, let's say we were asked to write a page that contained a button that listed the current date and time to the latest second. For demonstration purposes, when the user clicks on the button, we would like the date and time to be displayed as the button's new text.

Try It Out -- Creating an event handler

1. The first step would be to declare the ASP.NET button control. To do this, type the following text into our code editor:

<form id=SampleEvent method=post runat="server">    
 <asp:Button id="CurrentTimeButton" runat="server"    
   Text="Click for current time..." OnClick="UpdateTime" />    
</form>

2. Save this file as eventhandler.aspx. If you run this code in your browser right now, you'll see the following error message:

14_11_1.jpg

We get this error, because we have not yet defined our UpdateTime event handler. Let's do this now.

3. Open up eventhandler.aspx, and amend the code by adding the following opening section:

<script language="VB" runat="server">    
Public Sub UpdateTime (ByVal sender As Object, ByVal e As    
 system.EventArgs)    
' Perform custom logic here -- update the button text with    
current time    
CurrentTimeButton.Text = DateTime.Now.ToShortTimeString()    
End Sub    
</script>    
<form id=SampleEvent method=post runat="server">    
<asp:Button id="CurrentTimeButton" runat="server"    
Text="Click for current time..." OnClick="UpdateTime" />    
</form>

To find out all the properties, methods and events pertaining to the controls such as the ASP.NET Button control, take a look at the class browser.

4. Now if you run the code in your browser, you'll see the button we created, and when you click on it, you'll see the current time:

14_12_1.jpg

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links