User Controls

 
Chapter 16 - User Controls and Custom Controls
bySimon Robinsonet al.
Wrox Press 2002
  

User controls are controls that you create using ASP.NET code, just as you would in standard ASP.NET web pages. The difference is that once you have created a user control you can reuse it in multiple ASP.NET pages with a minimum of difficulty.

For example, let's say that you have created a page that displays some information from a database, perhaps information about an order. Instead of creating a fixed page that does this, it is possible to place the relevant code into a user control, and then insert that control into as many different web pages as you wish.

In addition, it is possible to define properties and methods for user controls. For instance, you could specify a property for the background color for displaying your database table in a web page, or a method to re-run a database query to check for changes.

Let's dive in and create a simple user control, discussing the relevant points as they come up, then build on it to see how we can add methods and properties.

A Simple User Control

In VS .NET, create a new web application called PCSUserCWebApp1 . Once the standard files have been generated, select the Project Add New Item... menu option, and add a Web User Control called PCSUserC1.ascx as shown:

click to expand

The files added to our project, with the extensions .ascx and .ascx.cs , work in a very similar way to the .aspx files we've seen already. The .ascx file will contain our ASP.NET code and look very similar to a normal .aspx file. The .ascx.cs file is our code-behind file, which defines the user control, much in the same way that forms are defined in .aspx.cs files.

.ascx files can be viewed in designer or HTML view just like .aspx files. Looking at the file in HTML view reveals an important difference: there is no HTML code-present, and in particular no < form > element. This is because user controls will be inserted inside ASP.NET forms in other files, and so don't need a < form > tag of their own. The generated code is as follows :

   <%@ Control Language="c#" AutoEventWireup="false" Codebehind="PCSUserC1.ascx.cs"     Inherits="PCSUserCWebApp1.PCSUserC1"     TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>   

This is very similar to the < %@ Page % > directive generated in .aspx files, except that Control is specified rather than Page , and a TargetSchema attribute is included. This attribute specifies what browser the control is being designed for, in this case Internet Explorer 5, which affects what items are available to add from the VS .NET toolbox.

Looking at the generated code in the .ascx.cs file reveals another important difference from ASP.NET pages: the class generated inherits from System.Web.UI.UserControl . Again, this is because the control will be used inside a form, it isn't a form itself.

Our simple control will be one that displays a graphic corresponding to one of the four standard suits in cards (club, diamond, heart, spade). The graphics required for this are shipped as part of VS .NET; you can find them in: C:\Program Files\Microsoft Visual Studio.NET\Common7\Graphics\bitmaps\assorted , with the filenames CLUB.BMP , DIAMOND.BMP , HEART.BMP , and SPADE.BMP . Copy these into your project's directory so that we can use them in a moment.

Let's add some code to our new control. In the HTML view of PCSUserC1.ascx add the following:

 <%@ Control Language="c#" AutoEventWireup="false" Codebehind="PCSUserC1.ascx.cs"     Inherits="PCSUserCWebApp1.PCSUserC1"     TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>   <table cellspacing=4>     <tr valign="middle">     <td>     <asp:Image Runat="server" ID="suitPic" ImageURL="club.bmp"/>     </td>     <td>     <asp:Label Runat="server" ID="suitLabel">Club</asp:Label>     </td>     </tr>     </table>   

This defines a default state for our control, which will be a picture of a club along with a label. Before we add any additional functionality we'll test this default by adding this control to our project web page WebForm1.aspx .

In order to use a custom control in a .aspx file, we first need to specify how we will refer to it, that is, the name of the tag that will represent the control in our HTML. To do this we use the < %@ Register % > directive at the top of the code as follows:

   <%@ Register TagPrefix="PCS" TagName="UserC1" Src="PCSUserC1.ascx" %>   

The TagPrefix and TagName attributes specify the tag name to use (in the form TagPrefix:"TagName" ), and we use the Src attribute to point to the file containing our user control. Now we can use our control by adding the following element:

 <form id="Form1" method="post" runat="server">   <PCS:UserC1 Runat="server" ID="myUserControl"/>   </form> 

User controls aren't declared by default in the code behind our form, so we also need to add the following declaration to WebForm1.aspx.cs :

 public class WebForm1 : System.Web.UI.Page    {   protected PCSUserC1 myUserControl;   ... 

This is all we need to do to test our user control, and running the project results in the following:

click to expand

As it stands this control groups two existing controls together, an image and a label in a table layout. As such it falls into the category of a composite control.

To gain control over the suit being displayed, we can use an attribute on the < PCS:UserC1 > element. Attributes on user control elements are automatically mapped to properties on user controls, so all we have to do to make this work is add a property to the code behind our control, PCSUserC1.ascx.cs . We'll call this property Suit , and let it take any suit value. To make it easier for us to represent the state of the control, we'll define an enumeration to hold the four suit names , inside the PCSUserCWebApp1 namespace in the PCSUserC1.ascx.cs file:

 namespace PCSUserCWebApp1 {    ...   public enum suit     {     club, diamond, heart, spade     }   ... } 

The PCSUserC1 class needs a member variable to hold the suit type, currentSuit :

 public class PCSUserC1 : System.Web.UI.UserControl    {       protected System.Web.UI.WebControls.Image suitPic;       protected System.Web.UI.WebControls.Label suitLabel;   protected suit currentSuit;   

And a property to access this member variable, Suit :

   public suit Suit     {     get     {     return currentSuit;     }     set     {     currentSuit = value;     suitPic.ImageUrl = currentSuit.ToString() + ".bmp";     suitLabel.Text = currentSuit.ToString();     }     }   

The set accessor here sets the URL of the image to one of the files we copied earlier, and the text displayed to the suit name.

Now the control is finished we need to add code to WebForm1.aspx to access this new property. We could simply specify the suit using the property we have just added:

 <PCS:UserC1 Runat="server" id="myUserControl" Suit="diamond"/> 

The ASP.NET processor is intelligent enough to get the correct enumeration item from the string provided. To make things a bit more interesting and interactive, though, we'll use a radio button list to select a suit:

 <form id="Form1" method="post" runat="server">          <PCS:UserC1 Runat="server" ID="myUserControl"/>   <asp:RadioButtonList Runat="server" ID="suitList"     AutoPostBack="True">     <asp:ListItem Value="club" Selected="True">Club</asp:ListItem>     <asp:ListItem Value="diamond">Diamond</asp:ListItem>     <asp:ListItem Value="heart">Heart</asp:ListItem>     <asp:ListItem Value="spade">Spade</asp:ListItem>     </asp:RadioButtonList>   </form> 

We also need to add an event handler for the SelectedIndexChanged event of the list, which we can do simply by double-clicking on the radio button list control in design view.

Note that we have set the AutoPostBack property of this list to True , as the suitList_SelectedIndexChanged() event handler won't be executed on the server unless a postback is in operation, and this control doesn't trigger a post back by default.

The suitList_SelectedIndexChanged() method needs the following code in WebForm1.aspx.cs :

 protected void suitList_SelectedIndexChanged(object sender,                                                    System.EventArgs e)       {   myUserControl.Suit = (suit)Enum.Parse(typeof(suit),     suitList.SelectedItem.Value);   } 

We know that the Value attributes on the < ListItem > elements represent valid values for the suit enumeration we defined earlier, so we simply parse these as enumeration types and use them as values of the Suit property of our user control. We cast the returned object type to suit using simple casing syntax, as this can't be achieved implicitly.

Now we can change the suit when we run our web application:

click to expand

Next we'll give our control some methods. Again, this is very simple; we just need to add methods to our PCSUserC1 class:

   public void Club()     {     Suit = suit.club;     }     public void Diamond()     {     Suit = suit.diamond;     }     public void Heart()     {     Suit = suit.heart;     }     public void Spade()     {     Suit = suit.spade;     }   

These four methods, Club() , Diamond() , Heart() , and Spade() , change the suit displayed on the screen to the respective suit clicked.

We'll call these functions from four ImageButton controls in our .aspx page:

 </asp:RadioButtonList>   <asp:ImageButton Runat="server" ID="clubButton"     ImageUrl="CLUB.BMP"     OnClick="clubButton_Click"/>     <asp:ImageButton Runat="server" ID="diamondButton"     ImageUrl="DIAMOND.BMP"     OnClick="diamondButton_Click"/>     <asp:ImageButton Runat="server" ID="heartButton"     ImageUrl="HEART.BMP"     OnClick="heartButton_Click"/>     <asp:ImageButton Runat="server" ID="spadeButton"     ImageUrl="SPADE.BMP"     OnClick="spadeButton_Click"/>   </form> 

With the following event handlers:

   protected void clubButton_Click(object sender,     System.Web.UI.ImageClickEventArgs e)     {     myUserControl.Club();     suitList.SelectedIndex = 0;     }     protected void diamondButton_Click(object sender,     System.Web.UI.ImageClickEventArgs e)     {     myUserControl.Diamond();     suitList.SelectedIndex = 1;     }     protected void heartButton_Click(object sender,     System.Web.UI.ImageClickEventArgs e)     {     myUserControl.Heart();     suitList.SelectedIndex = 2;     }     protected void spadeButton_Click(object sender,     System.Web.UI.ImageClickEventArgs e)     {     myUserControl.Spade();     suitList.SelectedIndex = 3;     }   

Now we have four new buttons we can use to change the suit:

click to expand

Now we've created our user control we can use it in any other web page simply by using the < %@ Register % > directive and the two source code files ( PCSUserC1.ascx and PCSUserC1.ascx.cs ) we have created for the control.

  


Professional C#. 2nd Edition
Performance Consulting: A Practical Guide for HR and Learning Professionals
ISBN: 1576754359
EAN: 2147483647
Year: 2002
Pages: 244

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net