Sams Teach Yourself ASP.NET in 21 Days, Second Edition
By Chris Payne
Table of Contents
Day 6.  Learning More About Web Forms

Whew, today was a long day! You learned a lot about the Web forms framework and how to extend it by creating your own server controls. You also learned the difference between creating controls at runtime and at design time, and now you should be familiar with both methods.

User controls are simply pieces of user interface code that are contained in files with the extension .ascx. Any existing ASP.NET page can be transformed into a user control by removing all <html>, <body>, and <form> tags, changing any @ Page directives to @ Control, and changing the file extension from .aspx to .ascx. User controls can and should contain the logic that controls the UI elements. This allows you to fully encapsulate a piece of UI functionality and easily implement it on any ASP.NET page. Custom controls allow you to create server controls that perform any type of functionality you want. These controls are used when no existing server controls fit your needs. They're created in VB.NET source files and must be compiled using the VB.NET compiler (see Day 15 for more information).

With custom controls, you can add state and event capabilities. The former is easy to implement. Simply use the state bag to store any properties of your control, instead of private variables. The latter is more complex, but luckily it's standard. You can write it once and simply copy-and-paste it to other controls.

You must register both user controls and custom controls with the @ Register directive before you can use them on your pages. The syntax is slightly different for each:

 'user control <%@ Register TagPrefix="Prefix" TagName="Name" src="filepath" %> 'custom control <%@ Register TagPrefix="Prefix" Namespace="Namespace" Assembly="Assembly"%> 

You can create server controls at runtime in addition to design time. This allows you to control the UI even in unforeseen circumstances, such as when you have too much data to fit in your existing UI. Regular server controls and custom controls can be created just like any other object in ASP.NET, with the dim statement. On the other hand, user controls must use the Page.LoadControl method to create new instances. This method returns a data type based on the filename of your user control's source file. Use a variable of this data type to assign properties to your control.

Tomorrow's lesson will complete this look at Web forms by examining the validation controls. These controls allow you to easily validate any user input before it can cause errors in your application. You'll be amazed at how easily you can force users to enter the information you want.


    Sams Teach Yourself ASP. NET in 21 Days
    Sams Teach Yourself ASP.NET in 21 Days (2nd Edition)
    ISBN: 0672324458
    EAN: 2147483647
    Year: 2003
    Pages: 307
    Authors: Chris Payne © 2008-2017.
    If you may any questions please contact us: