You are here:   Units 5 to 8 > 5. User Controls
  |  Login

UserControls

Minimize

User Controls


At times, you might need functionality in a control that is not provided by the built-in ASP.NET Web server controls. In those cases, you can create your own controls. You have two options. You can create:

  • User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.

  • Custom controls. A custom control is a class that you write that derives from Control or Web Control.

User controls are substantially easier to create than custom controls, because you can reuse existing controls. They make it particularly easy to create controls with complex user interface elements.

Creating User Controls


An ASP.NET Web user control is similar to a complete ASP.NET Web page (.aspx file), with both a user interface page and code. You create the user control in much the same way you create an ASP.NET page and then add the markup and child controls that you need. A user control can include code to manipulate its contents like a page can, including performing tasks such as data binding.

A user controls differs from an ASP.NET Web page in these ways:

  • The file name extension for the user control is .ascx.

  • Instead of an @Page directive, the user control contains an @Control directive that defines configuration and other properties.

  • User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET pages, as you would any control.

  • The user control does not have html, body, or form elements in it. These elements must be in the hosting page.

You can use the same HTML elements (except the html, body, or form elements) and Web controls on a user control that you do on an ASP.NET Web page. For example, if you are creating a user control to use as a toolbar, you can put a series of Button Web server controls onto the control and create event handlers for the buttons.

To create a UserControl you right click on the project and select add new item. You choose the language that you want to work with and from the templates you select Web User Control:

This example will show how to create a spinner control. This control is going use two button controls and a text box that can be used to rotate through a series of values. The basic layout will look something like this:

User Control Design
The design view of the spinner user controls. Notice this is very similar to creating a normal web page. The major difference is this is created in an ascx file
The design view of the spinner user controls. Notice this is very similar to creating a normal web page. The major difference is this is created in an ascx file
Spinner Control Markup
The markup for the spinner control
The markup for the spinner control

Adding Code


 

The spinner control will cycle through four colors based on the click events of the two buttons on the form. To keep track of the current state of the color a mechanism needs to be put in place to keep track of the variable value through post backs to the server.

If you have not figured this out yet, you should know that the web is stateless and so are ASP.NET pages. They are instantiated, executed, rendered, and disposed on every round trip to the server. You can add statefulness using techniques like storing state on the server in Session state or by posting a page back to itself.

Before ASP.NET, restoring the values back into the form fields across multiple postbacks was entirely the responsibility of the page developer who had to pick them out one-by-one, from the HTTP form and push them back into the fields. Happily, ASP.NET does this trick automatically eliminating a lot of grunt work and code for forms.

ViewState


 

 

ViewState is the mechanism ASP.NET uses to keep track of server control state values that don't otherwise post back as part of the HTTP form. For example, the text shown by a Label control is saved in ViewState by default. As a developer, you can bind data or programmatically set the Label just once when the page first loads, and on subsequent postbacks, the label text will be repopulated automatically from ViewState. So in addition to less grunt work and less code, the benefit of ViewState is often fewer trips to the database.

ViewState is a great way to track the state of a control across postbacks since it doesn't use server resources, doesn't time out, and works with any browser. If you are a control author, you'll definitely want to check out Maintaining State in a Control.

Page authors can also benefit from ViewState in much the same way. Occasionally your pages will contain UI state values that aren't stored by a control. You can track values in ViewState using programming syntax that is similar to that for Session and Cache:

// save in ViewState
ViewState["SortOrder"] = "DESC";

// read from ViewState
string sortOrder = (string)ViewState["SortOrder"];

This technique will be employed to keep track of the value of variables within the spinner control.

Back to the Code

 


 

 

The spinner control will have an int variable that will keep track of the color index. Appropriately it will be called currentColorIndex. The control will also need an array of colors to cycle through. In this example 4 colors will be used but this could certainly be expanded to do more.

Page_Load Event 


 

Page Load Event
The value of the color index is stored in a state variable.
The value of the color index is stored in a state variable.

In the page load event the property IsPostBack is used to see if the page has been freshly loaded or has been posted back from the spinner control. If it is has been posted back then the color index is loaded from the view state. If the page has not been posted back then the currentColorIndex variable is set to 0 and the displayColor method is called.

A Word About IsPostBack


 

All ASP.NET pages expose the IsPostBack property. This is a read-only Boolean property that indicates if the page or control is being loaded for the first time, or if it is being loaded in response to a client postback. Many expensive operations (such as getting data from a database or populating ListItems) must be performed only the first time the page or control is loaded. If the page is posted to the server and then reloaded, there is no need to repeat the operation.

Button Events And Other Things


 

The two button click events handle cycling through the colors. buttonUp goes to the next color in the list, buttonDown goes to the previous color in the list. You should note that this is what is called a circular queue in that if the buttonUp event gets to the last color it resets the currentColorIndex to 0. Likewise with the buttonDown event if the currentColorIndex goes below 0 it is reset back to the end of the color array.

The displayColor method does nothing more than change the color of the text in the TextBox and store the currentColorIndexValue in ViewState.

 

Button events
a cricular queue helps rotate through the colors
a cricular queue helps rotate through the colors

Using Your New Control


In order to use your new control you must do two things. One is that you need to register it in any page that uses it. This should be done at the top of the page under the Page directive. In the case of the Spinner the registration looks like this:

<%@ Register Src="/portals/5/~/Spinner.ascx" TagName="Spinner" TagPrefix="gasware" %>

This is a typical registration but needs some explanation

 Attribute Decription 
 Src  Src attribute is the virtual path to the user control. In this case it is the path to Spinner.ascx.
 TagName The TagName is the name for the user control. This name is used along with the tag prefix to uniquely identify the namespace for the control. In this example the name of the control is Spinner.
 TagPrefix  The TagPrefix determines a unique namespace for the user control. If multiple user controls on the page happen to have the same name, they can be differentiated from each other using this. In my example I used gasware but you can choose any name that you like for this attribute.

To add your control to a page you use the TagPrefix:TagName pair where you want the control to go:

<gasware:Spinner ID="spinner1" runat="server" />

Also note that you need to have the runat="server" for the control to work.

 

Registering the control
create a TagPrefix TagName pair to identify the control on the page
create a TagPrefix TagName pair to identify the control on the page
Spinner Control On Page
The spinner control in use
The spinner control in use

See The Code Run


Click on the image below to see the Spinner controls run

Spinner Control
The spinnner control running on the server
The spinnner control running on the server

Video - Creating a User Control


The video below demonstrates the step to create a user control
Creating A User Control
Create the TextLabel user control
Create the TextLabel user control