Completing a Web Form in ASP.NET - How to use page and control events
(Page 4 of 5 )
The first table in figure 2-15 presents some of the common events for working with web pages. The Init and Load events of a page occur whenever a page is requested from the server. The Init event occurs first, and it’s used by ASP.NET to restore the view state of the page and its controls. Because of that, you don’t usually create an event handler for this event. Instead, you add any initialization code to the event handler for the Load event. You’ll see how this works in the next figure.
In contrast, the PreRender event is raised after all the control events for the page have been processed. It’s the last event to occur before a page is rendered to HTML. In later chapters, you’ll see a couple of cases in which this event is useful.
The second table in this figure lists some of the common events for web server controls. When the user clicks a button, for example, the Click event of that control is raised. Then, the page is posted back to the server, the event handlers for the Init and Load events of the page are executed, if present, followed by the event handler for the Click event of the control that was clicked.
The TextChanged event occurs when the user changes the value in a text box. In most cases, you won’t code an event handler for the TextChanged event. However, you might code an event handler for the CheckedChanged event that occurs when the user clicks a radio button or checks a check box. You might also code an event handler for the SelectedIndexChanged event that occurs when the user selects an item from a drop-down list.
If you want the event handler for one of these events to be executed immediately when the event occurs, you can set the AutoPostBack property of the control to True. Then, the event handler will be executed after the Load and Init event handlers for the page. Note that if you don’t set the AutoPostBack property to True, the event is still raised, but the event handler isn’t executed until another user action causes the page to be posted to the server. Then, the event handlers for the Load and Init events of the page are executed, followed by the event handlers for the control events in the order they were raised.
In this figure, you can see the event handler for the Click event of the Clear button on the Future Value form. Note that the name for this event handler is btnClear_Click, which is the ID of the button followed by the name of the event. Remember, though, that the Handles clause actually determines what event or events the procedure responds to. In this procedure, the value in the drop-down list is reset to 50, and the text boxes and label are reset to empty strings.
Incidentally, using the Handles clause is the default method for wiring events to their event handlers. However, you can also wire an event to an event handler by naming the event handler on the event attribute of a control. Although you’ll learn how this works in chapter 6, there’s usually no reason to change from using the Handles clause.
Common ASP.NET page events
Event | Procedure name | Occurs when… |
Init | Page_Init | A page is requested from the server. This event is raised before the view state of the page controls has been restored. |
Load | Page_Load | A page is requested from the server, after all controls have been initialized and view state has been restored. This is the event you typically use to perform initialization operations such as retrieving data and initializing form controls. |
PreRender | Page_PreRender | All the control events for the page have been processed but before the HTML that will be sent back to the browser is generated. |
Common ASP.NET control events
Event | Occurs when… |
Click | The user clicks a button, link button, or image button control. |
TextChanged | The user changes the value in a text box. |
CheckedChanged | The user selects a radio button in a group of radio buttons or selects or unselects a check box. |
SelectedIndexChanged | The user selects an item from a list box, a drop-down list, a check box list, or a radio button list. |
Code for the Click event of the btnClear button
Protected Sub btnClear_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnClear.Click
ddlMonthlyInvestment.Text = 50
txtInterestRate.Text = ""
txtYears.Text = ""
lblFutureValue.Text = ""
End Sub
Figure 2-15. How to use page and control events
Description
- All of the events associated with an ASP.NET web page and its server controls are executed on the server. Because of that, the page must be posted back to the server to process any event for which you’ve coded an event handler.
- When a page is posted back to the server, the Init and Load events are always raised so any event handlers for those events are run first. Next, the event handlers for any control events that were raised are executed in the ordered they were raised. When these event handlers finish, the PreRender event is raised and any event handler for that event is run.
All of the events associated with an ASP.NET web page and its server controls are executed on the server. Because of that, the page must be posted back to the server to process any event for which you’ve coded an event handler.
The Visual Basic code for the Future Value form
Figure 2-16 presents the complete Visual Basic code for the code-behind file of the Future Value form. It consists of three event handlers that handle the Load event for the page and the Click events of the Calculate and Clear buttons. This code also includes a function procedure named FutureValue that is called by the event handler for the Click event of the Calculate button.
In this code, I’ve highlighted the two page properties that are commonly tested in the code for web forms. The first one is the IsPostBack property that’s used in the Page_Load procedure. If it is True, it means that the page is being posted back from the user. If it is False, it means that the page is being requested by the user for the first time.
As a result, the statements within the If statement in the Page_Load procedure are only executed if the page is being requested for the first time. In that case, the values 50 through 500 are added to the drop-down list. For all subsequent requests by that user, the IsPostBack property will be True so the values aren’t added to the drop-down list.
The other page property that’s commonly tested is the IsValid property. It’s useful when the user’s browser doesn’t support the script for the validation controls. In that case, the application has to rely on the validation that’s always done on the server. Then, if IsValid is True, it means that all of the input data is valid. But if IsValid is False, it means that one or more controls contain invalid input data so the processing shouldn’t be done.
In the btnCalculate_Click procedure, you can see how the IsValid test is used. If it isn’t True, the processing isn’t done. But otherwise, this procedure gets the years and interest rate values from the text boxes and converts them to monthly units. Then, it uses the SelectedValue property of the drop-down list to get the value of the selected item, which represents the investment amount. Last, it calls the FutureValue function to calculate the future value, uses the FormatCurrency method to format the future value, and puts the formatted value in the label of the form. When this procedure ends, the web form is sent back to the user’s browser.
With the exception of the IsPostBack and IsValid properties, this is all standard Visual Basic code so you shouldn’t have any trouble following it. But if you do, you can quickly upgrade your Visual Basic skills by getting our latest Visual Basic book.
The Visual Basic code for the Future Value form
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim iIndex As Integer
For iIndex = 50 To 500 Step 50
ddlMonthlyInvestment. Items.Add(iIndex)
Next iIndex
End If
End Sub
Protected Sub btnCalculate_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim iMonths As Integer
Dim dInterestRate, dMonthlyInvestment As Decimal
Dim dFutureValue As Decimal
If IsValid Then
iMonths = txtYears.Text * 12
dInterestRate = txtInterestRate.Text / 12 / 100
dMonthlyInvestment = ddlMonthlyInvestment.SelectedValue
dFutureValue = FutureValue(iMonths, dInterestRate, dMonthlyInvestment)
lblFutureValue.Text = FormatCurrency(dFutureValue)
End If
End Sub
Private Function FutureValue(ByVal Months As Integer, _
ByVal InterestRate As Decimal, _
ByVal MonthlyInvestment As Decimal) As Decimal
Dim iIndex As Integer
Dim dFutureValue As Decimal
For iIndex = 1 To Months
dFutureValue = (dFutureValue + MonthlyInvestment) _
* (1 + InterestRate)
Next iIndex
Return dFutureValue
End Function
Protected Sub btnClear_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnClear.Click
ddlMonthlyInvestment.Text = 50
txtInterestRate.Text = ""
txtYears.Text = ""
lblFutureValue.Text = ""
End Sub
End Class
Figure 2-16. The Visual Basic code for the Future Value form
How to test a web application
After you design the forms and develop the code for a web application, you need to test it to be sure it works properly. Then, if you discover any errors in the application, you can debug it, correct the errors, and test it again.
In chapter 4, you’ll learn all the skills you need to test and debug a web application. For now, I just want to show you how to run a web site with the built-in development server so you can test any applications that you develop for this chapter. Then, I’ll show you the HTML code that’s sent to the browser so you can see how that works.
Next: How to run a web site with the built-in development server >>
More ASP.NET Articles
More By Murach Publishing
|
This article is excerpted from the book Murach's ASP.NET 2.0 Web Programming with VB2005, written by Doug Lowe (Murach, 2006; ISBN: 1890774324). Check it out today at your favorite bookstore. Buy this book now.
|
|