ASP.NET
  Home arrow ASP.NET arrow Page 4 - Completing a Web Form in ASP.NET
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Completing a Web Form in ASP.NET
By: Murach Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 23
    2006-06-15

    Table of Contents:
  • Completing a Web Form in ASP.NET
  • How to use the required field validator
  • How to add code to a form
  • How to use page and control events
  • How to run a web site with the built-in development server

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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

    1. 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.
    2. 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.

    More ASP.NET Articles
    More By Murach Publishing


       · This article is an excerpt from the book "Murach's ASP.NET 2.0 Web Programming with...
     

    Buy this book now. 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.

    ASP.NET ARTICLES

    - Developing a Mini ASP.NET AJAX Server Centri...
    - Disadvantages of the ASP.NET MVC Framework
    - Advantages of the ASP.NET MVC Approach
    - ASP.NET Web Forms Weaknesses
    - ASP.NET Web Forms Meets ASP.NET MVC
    - Source Code for Saving and Retrieving Data w...
    - Using GridView to Save and Retrieve Data wit...
    - Handling Dynamic Images in ASP.NET 3.5 AJAX ...
    - Retrieving Data with AJAX and the GridView C...
    - Playing with Images in ASP.NET 3.5 AJAX Appl...
    - Saving and Retrieving Data with AJAX
    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT