Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Using Code Behind

Using components is an excellent method of moving your application logic outside your ASP.NET pages. However, as you have seen, components have one serious shortcoming. Because you cannot directly refer to the controls contained in an ASP.NET page from a component, you cannot move all your application logic out of the page.

In this section, you learn about a second method of dividing presentation content from code that remedies this deficiency. You learn how to take advantage of a feature of ASP.NET pages called code-behind.

You can use code-behind to cleanly divide an ASP.NET page into two files. One file contains the presentation content, and the second file, called the code-behind file, contains all the application logic.

Start with a page that has both its presentation content and application code jumbled together in one file. This page is shown in Listing 11.

Listing 11—Jumble.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 lblMessage.Text = "Hello!"
End Sub

</Script>

<html>
<head><title>Jumble.aspx</title></head>
<body>

<form Runat="Server">

<asp:Button
 Text="Click Here!"
 OnClick="Button_Click"
 Runat="Server" />

<p>

<asp:Label
 ID="lblMessage"
 Runat="Server" />

</form>

</body>
</html>

The page in Listing 11 contains one Button control and one Label control. When you click the button, the Button_Click subroutine executes and a message is assigned to the label.

Now, you can divide this page into separate presentation and code-behind files. The presentation file is simple; it just contains everything but the Button_Click subroutine. It also contains an additional page directive at the top of the file.

Listing 12—Presentation.aspx

<%@ Page Inherits="myCodeBehind" src="myCodeBehind.vb" %>
<html>
<head><title>Presentation.aspx</title></head>
<body>

<form Runat="Server">

<asp:Button
 Text="Click Here!"
 OnClick="Button_Click"
 Runat="Server" />

<p>

<asp:Label
 ID="lblMessage"
 Runat="Server" />

</form>

</body>
</html>

The code behind file, contained in Listing 13, is a little more complicated. It consists of an uncompiled Visual Basic class file.

Listing 13—myCodeBehind.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class myCodeBehind
 Inherits Page

 Protected WithEvents lblMessage As Label

 Sub Button_Click( s As Object, e As EventArgs )
  lblMessage.Text = "Hello!"
 End Sub

End Class

That's it. That's all you need to do to cleanly divide a page into separate files for presentation content and application logic. If you save the Presentation.aspx and myCodeBehind.vb files anywhere on your Web server, you can immediately open the Presentation.aspx file in a Web browser, and the page will work as expected.

Notice that you do not even have to compile the code behind file. The Visual Basic class contained in the code behind file is compiled automatically when you request the Presentation.aspx page.

How Code Behind Really Works

If you look closely at the Visual Basic class declared in the code-behind file in the preceding section, you notice that the myCodeBehind class inherits from the Page class. The class definition for myCodeBehind begins with the following statement:

Inherits Page

When you create a code-behind file, you are actually creating an instance of an ASP.NET page. You're explicitly building a new ASP.NET page in a class file by inheriting from the Page class.

Code behind pages use an additional level of inheritance. The page used for the presentation content in the preceding section, Presentation.aspx, inherits from the code-behind file. The first line of Presentation.aspx is as follows:

<%@ page inherits="myCodeBehind" src="myCodeBehind.vb" %>

The presentation page inherits all the properties, methods, and events of the code-behind file. When you click the button, the Button_Click subroutine executes because the presentation page is inherited from a class that contains this subroutine.

So, the code-behind file inherits from the Page class, and the presentation file inherits from the code-behind file. Because this hierarchy of inheritance exists, all the properties, methods, and events of the Page class are available in the code-behind file, and all the properties, methods, and events in the code-behind file are available to the presentation file.

When using code-behind files, you must be careful to declare an instance of each control used in the presentation file within the code-behind file. For example, in the code-behind file, you refer to the lblMessage control in the Button_Click subroutine. So, you have to explicitly declare the control in the code-behind file like this:

Protected WithEvents lblMessage As Label

If you neglect to include this declaration, you would receive the error The name 'lblMessage' is not declared when attempting to open the presentation page in a browser.

Compiling Code Behind Files

You don't need to compile a code-behind file. The class file contained in a code-behind file is compiled automatically when you request the presentation page. If you prefer, however, there is nothing to prevent you from compiling it. For example, to compile a code behind file named CodeBehind.vb, execute the following statement from a DOS prompt in the same directory as your code behind file:

vbc /t:library /r:system.dll,system.web.dll CodeBehind.vb

This statement compiles a code behind file named CodeBehind.vb into a file named CodeBehind.dll. The /t option indicates that a DLL file should be created. The /r option references the system.dll assembly and system.web.dll assembly. (All the Web control classes inhabit this assembly.)

After you compile the code-behind file into CodeBehind.dll, you need to move this file to your application's /BIN directory.

Finally, modify the page directive on the presentation page. Change the page directive from

<%@ Page Inherits="CodeBehind" src="CodeBehind.vb" %>

to

<%@ page inherits="CodeBehind" %>

You no longer need the src attribute because the compiled code-behind file is located in the /BIN directory. The compiled classes in the /BIN directory are automatically available to use in all the ASP.NET pages in an application.

Inheriting Multiple Pages from a Code Behind File

You can inherit multiple presentation pages from the same code-behind file. In fact, if you really want to, you could inherit all the pages in your Web site from a single code-behind file.

Why is this capability useful? Imagine that you have a set of functions and subroutines that you need to call in almost every page. You can place the functions and subroutines in your code-behind file, and they are immediately available in any page that inherits from the code-behind file.

The code-behind file in Listing 14, for example, has one subroutine and one function. The subroutine is the standard Page_Load subroutine that executes whenever a page is first loaded. The utility function named HeaderMessage() returns the current date.

Listing 14—CodeBehindMultiple.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class CodeBehindMultiple
 Inherits Page

 Protected WithEvents lblHeader As Label

 Overridable Sub Page_Load
  lblHeader.Text = HeaderMessage()
 End Sub


 Function HeaderMessage() As String
  Dim strMessage As String

  strMessage = "Welcome to this Web site!<br>"
  strMessage &= "The current date is "
  strMessage &= DateTime.Now.ToString( "D" )
  Return strMessage
 End Function

End Class

Any page that derives from the code-behind file in Listing 14 inherits both the Page_Load subroutine and HeaderMessage() function. For example, the presentation page in Listing 15 automatically uses the Page_Load subroutine from the code-behind file.

Listing 15—PresentationMultiple1.aspx

<%@ Page Inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %>

<html>
<head><title>PresentationMultiple1.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="lblHeader"
 Runat="Server" />

<h2>Page 1</h2>

</form>
</body>
</html>

When you open the page contained in Listing 15, the Page_Load subroutine from the code behind file executes, and the header Label is assigned the text from the HeaderText() function.

Now, imagine that you want to use the Page_Load subroutine declared in the code behind file in some pages that inherit from the code behind file but not others. Because you declared the Page_Load subroutine as Overridable, you can override it in a presentation page.

The page in Listing 16, for example, overrides the Page_Load subroutine with its own Page_Load subroutine and displays a custom message in the header Label.

Listing 16—PresentationMultiple2.aspx

<%@ page Inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %>

<Script Runat="Server">

Overrides Sub Page_Load
 lblHeader.Text = "Who cares about the current date?"
End Sub

</Script>


<html>
<head><title>PresentationMultiple2.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="lblHeader"
 Runat="Server" />

<h2>Page 2</h2>

</form>
</body>
</html>

Notice that the Page_Load subroutine uses the Overrides modifier, which overrides the Page_Load subroutine declared in the code-behind file. You can set it up this way because the Page_Load subroutine was declared with the Overridable modifier.

Now, try one last example. Imagine that you want to create a page that executes the Page_Load subroutine in the code-behind file but also executes a Page_Load subroutine of its own. You can extend the subroutine in the code-behind file within a presentation file by overriding the original subroutine and calling the original subroutine in the new subroutine. In other words, you can extend the code-behind subroutine in your presentation file.

The presentation page in Listing 17 illustrates how you would do so.

Listing 17—PresentationMultiple3.aspx

<%@ page inherits="CodeBehindMultiple" src="CodeBehindMultiple.vb" %>

<Script Runat="Server">

Overrides Sub Page_Load
 myBase.Page_Load
 lblHeader.Text &= "<br>And the current time is "
 lblHeader.Text &= Now.ToString( "t" )
End Sub

</Script>

<html>
<head><title>PresentationMultiple3.aspx.aspx</title></head>
<body>

<form Runat="Server">

<asp:Label
 ID="lblHeader"
 Runat="Server" />

<h2>Page 3</h2>

</form>
</body>
</html>

In Listing 17, the Page_Load subroutine overrides the Page_Load subroutine from the code-behind file. However, notice this statement:

myBase.Page_Load

This statement invokes the Page_Load subroutine in the code behind file. The Visual Basic myBase keyword refers to the base class that the current class is derived from. Therefore, when the page contained in Listing 17 is opened in a browser, the Page_Load subroutines in both the code behind file and presentation file are executed. The page in Figure 5 is displayed.

Figure 5 Extending a code-behind subroutine.

Compiling a Complete ASP.NET Page

In this article, you have examined various methods of moving the application logic out of an ASP.NET page and placing it in a separate file. In this section, I want to discuss an extreme case. How would you go about compiling all of an ASP.NET page, including both the presentation content and application code?

You might want to compile a complete page in several circumstances. For example, imagine that you have developed an e-Commerce Web site, and you want to sell the site to multiple clients. When you distribute the site, you might not want the clients to be able to easily view the source code. If you compile all the pages in your application, all the Visual Basic source code is hidden from view.

You can compile an ASP.NET page by placing all its contents into a code-behind file. In the code-behind file, you must explicitly declare all the controls and all the static content that appears in the page.

The code-behind file in Listing 18 contains a complete ASP.NET page in a Visual Basic class.

Listing 18—myPage.vb

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class myPage
 Inherits Page

 Dim txtTextBox As New TextBox
 Dim lblLabel As New Label

 Protected Overrides Sub CreateChildControls

 ' Add Opening HTML Tags
 Dim strOpenHTML As String
 strOpenHTML = "<html><head><title>My Page</title></head>"
 strOpenHTML &= "<body>Enter some text:"
 Controls.Add( New LiteralControl( strOpenHTML ) )

 ' Add HTMLForm Tag
 Dim frmForm As New HTMLForm
 frmForm.ID = "myForm"
 Controls.Add( frmForm )


 ' Add a TextBox
 txtTextBox.ID = "myTextBox"
 frmForm.Controls.Add( txtTextBox )

 ' Add a Button
 Dim btnButton As New Button
 btnButton.Text = "Click Here!"
 AddHandler btnButton.Click, AddressOf Button_Click
 frmForm.Controls.Add( btnButton )

 ' Add Page Break
 frmForm.Controls.Add( New LiteralControl( "<p>" ) )

 ' Add a Label
 lblLabel.ID = "myLabel"
 frmForm.Controls.Add( lblLabel )

 ' Add Closing HTML Tags
 Dim strCloseHTML As String
 strCloseHTML = "</form></body></html>"
 Controls.Add( New LiteralControl( strCloseHTML ) )

 End Sub

 Sub Button_Click( s As Object, e As EventArgs )
  lblLabel.Text = txtTextBox.Text
 End Sub

End Class

The bulk of the code in Listing 18 is contained in a subroutine called CreateChildControls. In this subroutine, you create each of the controls that you want to appear in your ASP.NET page.

To add static content to the page, you use the LiteralControl control. For example, you use LiteralControl to create the opening HTML tags at the beginning of the CreateChildControls subroutine and the closing HTML tags at the end of the subroutine.

You also add all the Web controls to the page within the CreateChildControls subroutine. First, you add an HTMLForm control to the page's Controls collection. Next, you add TextBox, Button, and Label controls to the HTMLForm's Controls collection.

Finally, your page class contains a subroutine named Button_Click. This subroutine is executed when you click the button. The Button_Click subroutine assigns whatever text was entered into the TextBox control to the Label control.

To wire up the Button_Click control to the Button control, you use the following statement:

AddHandler btnButton.Click, AddressOf Button_Click 

This statement adds an event handler to the Click event of the Button control. It associates the Button_Click subroutine with the Click event. So, whenever the button is clicked, the Button_Click subroutine is executed.

After you create the page class in Listing 18, you can compile it by using the following statement:

vbc /t:library /r:system.dll,system.web.dll myPage.vb

After the page is compiled, you need to move it to your application's /BIN directory.

Finally, to request the compiled page in a Web browser, you have to create one additional file. This file is contained in Listing 19.

Listing 19—ShowMyPage.aspx

<%@ Page inherits="myPage" %>

As you can see, the ShowMyPage.aspx file contains a single line; it's a page directive indicating that the current page should inherit from the myPage class. When you open ShowMyPage.aspx in a Web browser, the ASP.NET page created in the code behind file is displayed.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020