15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1188 ❘ ChaPTer 41 Asp.net feAtures<br />

<br />

Club<br />

<br />

<br />

<br />

This defines a default state for your control, which is a picture of a club along with a label. The ~ in the path<br />

to the image means “start at the root directory of the web site.” Before you add functionality, you will test<br />

this default by adding this control to a web page, so before continuing, add a new web page called Default<br />

.aspx to the web site.<br />

To use a custom control in an .aspx file, you first need to specify how you will refer to it, that is, the name<br />

of the tag that will represent the control in your HTML. To do this, you use the directive<br />

at the top of the code in Default.aspx, as follows:<br />

<br />

code snippet PCSUserCWebApp1/Default.aspx<br />

The TagPrefix <strong>and</strong> TagName attributes specify the tag name to use (in the form ),<br />

<strong>and</strong> you use the Src attribute to point to the file containing your user control. Now you can use the control<br />

by replacing the existing element in the file with code as follows adding the following element:<br />

<br />

<br />

<br />

<br />

<br />

This is all you need to do to test your user control. Figure 41-1 shows the results of running this code.<br />

figure 41-1<br />

As it st<strong>and</strong>s, this control groups two existing controls, an image <strong>and</strong> a label, in a table layout. Therefore, it<br />

falls into the category of a composite control.<br />

Adding a Suit Property<br />

To gain control over the displayed suit, you can use an attribute on the element. Attributes<br />

on user control elements are automatically mapped to properties on user controls, so all you have to do to<br />

make this work is add a property to the code behind your control, PCSUserC1.ascx.cs. Call this property<br />

Suit, <strong>and</strong> let it take any suit value. To make it easier for you to represent the state of the control, you define<br />

an enumeration to hold the four suit names. The best way to do this is to add an App_Code directory to your<br />

web site, <strong>and</strong> then add a .cs file called Suit.cs in this directory. App_Code is another “special” directory,<br />

like App_Data, whose functionality is defined for you — in this case it holds additional code files for your<br />

web site. You can add this directory by right-clicking the web site in Solution Explorer <strong>and</strong> clicking Add<br />

ASP.<strong>NET</strong> Folder ➪ App_Code. When you have done this, add Suit.cs with code as follows:<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!