Tải bản đầy đủ (.pdf) (77 trang)

Beginning asp net 2.0 with c phần 6 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.67 MB, 77 trang )

Componentization
You’ll see how you can manipulate all of these controls in the same way as you might expect to when
using a single file.

Try It Out
Creating a Code-Behind File
1. Open VWD and create a new web site called TestCodeBehind in the Chapter directory
(C:\BegASPNET2\Chapters\Begin\Chapter10).

2.

Go to Solution Explorer and click the plus symbol (+) next to Default.aspx to expand the tree
to reveal the file Default.aspx.cs (refer to Figure 10-1).
Again, Default.aspx is the only file that has the code-behind file automatically
created for you. If you create another Web Form, you must make sure to check the
Place Code in a Separate File option, which is unchecked by default.

3.

Go back to the Default.aspx file and add two Label controls, a TextBox control, and a
Button control, as shown in Figure 10-2.

Figure 10-2

353


Chapter 10
Adjust the source HTML to read as follows:
life, the universe and everything?:”></asp:Label>





<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox>



<asp:Button ID=”Button1” runat=”server” Text=”Submit” />



<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>

4.

Go back to Design View and double-click anywhere on the background of Default.aspx other
than on the controls. Doing so will open up into the code-behind file, shown in Figure 10-3.

Figure 10-3

5.

Add the following code to the Page_Load event handler:
if (Page.IsPostBack)
{
if (TextBox1.Text == “42”)
Label2.Text = “So you read Douglas Adams as well...”;
else
{


354


Componentization
Label2.Text = “No, I’m not sure that’s it”;
}
}

6.

Click the green arrow to run it. You may get a textbox asking whether or not to add a new
Web.config file or run without debugging. Click the former.

7.

Enter a value or lengthier sentence into the text box, as shown in Figure 10-4.

Figure 10-4

How It Works
It all seems very simple — instead of putting your code within <script> tags, you place it within a separate page, connected by the Page directive tag. Indeed, if you check at the top of the Source View for
Default.aspx, you can see that the following was already created:
<%@Page ... CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

This refers to the code-behind file Default.aspx.cs. There the following code is run when the
Page_Load event is called (when the page is viewed). This is just the normal kind of code talked about
in Chapter 9:
if (Page.IsPostBack)
{
if (TextBox1.Text == “42”)

Label2.Text = “So you read Douglas Adams as well...”;
else
{
Label2.Text = “No, I’m not sure that’s it”;
}
}

It says if the page has been posted back (submitted), check the contents of the TextBox control. If it
equals 42, then you have your correct answer, and you set the Label2 control’s Text property accordingly. If the contents of the TextBox control do not equal 42, you display a different answer (“No, I’m
not sure that’s it”).
However, there is a bit more going on beneath the covers, namely the method by which your code is
compiled.

355


Chapter 10

Compilation in ASP.NET 2.0
Compilation is another one of those subjects that this book doesn’t go into in depth, because you don’t
need to know too much about it. However, you should be aware of its presence. When you submit your
Web Form to the server, your Web Form and ASP.NET pages first have to be translated into a language
the server can understand. This is known as compilation. You can see how this process works in .NET 2.0
in Figure 10-5.

Disk

ASP.NET page

Compiler


Request

.NET CLR
Runtime
Intermediate Code
Response
Figure 10-5

The compiler changes your code into something known as intermediate code, or Microsoft Intermediate
Language (MSIL). This language is something that is independent of any PC it is run on. The .NET CLR
(Common Language Runtime) is able to take this intermediate code and change it into executable code
that it can run and provide output for. The output is then sent back to the user as a response. (There’s
actually a bit more to this process, as you’ll see in Chapter 14.)
During the process of compilation, your pages are approved syntactically, so if you’ve made any typos
such as the following, they will be spotted at compile time:
if (Paige.IsPostBack)

Your code can be compiled in two ways:


356

Pre-Runtime Compilation: The “normal” way (or the “old way,” — the default way in ASP.NET
1.1). Code-behind files are compiled into an assembly and stored in the \bin directory. Web
Forms and .aspx pages are compiled when needed.


Componentization



Full Runtime Compilation: Code-behind files and any other associated code can now be placed
in the App_Code folder. ASP.NET 2.0 will then create and maintain references to the assembly
that is generated from these files at runtime.

There is actually a third option called deployment pre-compilation, which is for full
compilation of your project prior to deployment. You’ll learn a little more about this
in Chapter 16.

The App_Code Folder
If you create an App_Code folder in your project, any code you place in that project will automatically be
compiled when you run the project. It’s a far more robust solution than the old \bin folder used by
ASP.NET 1.x, and for that reason you should use it for any code other than code-behind. The reason you
should not use it for code-behind is that it is easier in VWD to keep your code files attached to the page
they are related to; otherwise viewing them could be a pain.
So not only can you organize your code and in which pages it is placed, but ASP.NET 2.0 dictates a
different structure for ordering where those pages are placed.

Data Layers
You’ve looked at how code and content can be successfully separated, but there is a third dimension to
our discussions, namely that of the data. Throughout this book, we’ve paused to reflect briefly on various aspects of the history of the Internet and the Web, while trying to keep you away from a huge lecture on the entire subject. However, another quick history lecture is in order here to help you understand
the purpose of the next ASP.NET 2.0 feature.

Two-Tier Applications
Rather than rewinding too far back, let’s jump in halfway. When HTML started getting beyond the universities, it became necessary to provide something more than just static text and images. One of the first
ways in which web pages were made dynamic was to enable them to access a database. The browser
was one tier, and the database was the second tier. In this scenario, the browser dealt with rules about
the business or application and user interface.

The term business rules is used to encompass any part of the application logic that

isn’t the user interface or the database. If the application isn’t being used for a business, then the term application logic might be more applicable, although they mean
the same thing.

The data retrieval and manipulation was performed by another separate database application, such as
SQL Server or Microsoft Access. It would handle the data storage and retrieval device for the application. These two-tier applications were also commonly know as client-server applications. A typical clientserver application is depicted in Figure 10-6.

357


Chapter 10
REQUEST
Server

Client

RESPONSE
Figure 10-6

The other popular variation on the two-tier application saw the business rules (application logic) being
executed on the database system. Such applications would commonly use stored procedures to manipulate
the database (or in some cases triggers). A stored procedure is a query that is stored on the database. It
can be called by the client application and then run on the server. It would contain rules about the business as well. For example, if you had a league table on Wrox United that awarded three points for a win
and one point for a draw, then in the database query, it would somehow have to record that when one
side scores more goals than another side, it is worth three points. This is a business rule. It doesn’t matter to the database how many points you add on to the win; however, your league table would fail to
work properly if you added two or five points for a win.

Three-Tier Applications
The big difference with three-tier applications is that business rules are no longer located on either the
client or the database. They are stored and run on a system in between the client and the server. The
advantage of this is that the business rules server can ensure that all of the business processing is done

correctly. There is now a third layer interface, business rules and data. The introduction of the data tier is
illustrated in Figure 10-7.
REQUEST
Server

Client

BUSINESS
RULES

RESPONSE

RECORDS

QUERY

Data
Source
Figure 10-7

In a three-tier application, the client never accesses the data storage system directly. You can make
changes to the business rules and this would mean you could change any part of the system without
having to alter the other two parts. As the three different sections of the application communicate via
interfaces, and as long as the interface between the code and application front-end remains the same,
the internal workings of each part can be changed without affecting the rest of the application. The

358


Componentization

advantages of doing this are similar to those for keeping code and content separate. Typically, a database
is managed by a database administrator (DBA), and it might even be managed by a separate company.
The web developer as jack-of-all-trades would previously have been required to know the intimate
workings of the database, when really they shouldn’t be interfering there at all. So this brings you to the
end of your little excursion, because you can now look at a new feature in ASP.NET 2.0 that allows you
to separate your applications more simply into three tiers.

What’s New in ASP.NET 2.0
In ASP.NET 2.0, you are no longer restricted to binding only to data controls. You can also bind to separate business controls via the ObjectDataSource control.

Using the ObjectDataSource Control
The new ASP.NET ObjectDataSource control enables you to declaratively bind data controls such as
the GridView, DataList, and DropDownList controls to a separate business control or a data component. Previously, you could only bind the controls directly to a database. This new development enables
the separation of your business rules from your content and your data.
ObjectDataSource is a more difficult control to explain than a GridView or DropDownList control, so
rather than wasting excessive verbiage, it’s quicker to show you exactly what the ObjectDataSource

control does in an example. You’re actually going to do two examples to show it in action. In the first
example, you’ll see how to create a data component to return a list of players from the Players table. This
Try It Out is split into two sections: the first section where you create the ObjectDataSource itself and
the second where you bind the ObjectDataSource control to a GridView control. The resulting output
will be completely non-editable. In the second example, you’ll use the Try It Out to create a data component that can not only read from the Wrox United database but also write data to it. You’ll create and
bind the data component in this same example that will make it quite lengthy.
The data component that you create in both examples will consist of an XSD schema file (.xsd). This file
describes the data you require and defines which methods will be used to read and write data. This
doesn’t require any code or knowledge of XML schemas because when you run the application, the .xsd
file is compiled for you and performs all of the tasks needed.
Start by creating the data component for the read-only example.

Try It Out

Creating the Data Component
1. Open Visual Web Developer and select Open Web Site. From the C:\BegASPNet2\Chapters\
Begin\Chapter10 folder, select ObjectDataSource and click OK.

2.

In Solution Explorer, right-click the name of your web site, select Add ASP.NET Folder, and
select App_Code.

3.
4.
5.
6.

Right-click the App_Code folder and select Add New Item from the list.
From the Visual Studio installed templates, click DataSet.
Rename the DataSet ods.xsd and click Add.
VWD starts the TableAdapter Configuration Wizard. (Be patient here, because this one really
does take a while to kick in.) When the wizard finally arrives, select ConnectionString
(Web.config) from the drop-down list (see Figure 10-8) and click Next.

359


Chapter 10

Figure 10-8

7.


Next you get a page where you can choose to use SQL statements or stored procedures. Select
the Use SQL statements radio button (as shown in Figure 10-9) and click Next.

Figure 10-9

360


Componentization
8.

On the next wizard screen, you can define the SQL statement. Type the following SQL statement
into the “What data should be loaded into the table” area of the dialog box:

SELECT PlayerID, FirstName, LastName, Position, DateJoined, DateLeft FROM Players

9.

After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable check box and make sure that the Return a
DataTable check box is checked (see Figure 10-10). In the Method name box, type GetPlayers.
This method is used later to retrieve the data. Uncheck the final check box.

Figure 10-10

10.

Click Finish. In Figure 10-11, you can see the data component in the designer. It shows both the
data you selected and the method you created.

Figure 10-11


11.
12.

Save the data component and close the component designer.
Select Build➪Build Web Site to compile the component. (Note that this won’t produce anything
viewable.)

361


Chapter 10
How It Works
The data component is now usable as a data source within a Web Form. You’ve used the wizard to create
the component for you, to select the fields from the database, and also to name the method by which you
want to be able to call this component.
Thenext step is to bind to this component. To do this, you can create and configure an
ObjectDataSource control. You can then add controls, such as the GridView control, to the page and
bind them to the data source control.

Try It Out
Binding to the ObjectDataSource Control
1. Open the Default.aspx from Solution Explorer and switch to Design View.
2. Open the Toolbox and from the Data section drag an ObjectDataSource control onto the page.
3. Select the Toolbox again, and from the Data section drag a GridView control onto the page.
4. Click the black arrow in the top-right corner of the ObjectDataSource control. The Common
Tasks box appears with the words “Configure Data Source.” Click this.

5.


In the dialog box that appears, there is a single drop-down list asking you to choose your
business object (see Figure 10-12). There should only be one, the odsTableAdapters.
PlayersTableAdapter. Select it and click Next.

Figure 10-12

6.

362

On the next screen (shown in Figure 10-13), under the Select tab in the Choose a method dropdown box, the GetPlayers(), returns PlayersDataTable method is displayed. Select it
and click Finish (the other methods are automatically picked for you).


Componentization

Figure 10-13

7.

Click the black arrow on the top-right corner of the GridView control and from the Choose Data
Source list that appears, select ObjectDataSource1. The Grid will update in Design View.

8.
9.

Open the Properties window and check that the DataKeyNames property is set to PlayerID.
Run the application, and you will see Figure 10-14 in your browser.

Figure 10-14


363


Chapter 10
How It Works
You started by creating an instance of an ObjectDataSource control. To give it its functionality, you
attached it to the GetPlayers() method that was specified in the data component. The GetPlayers()
method was created in the previous Try It Out. This method returns the results of the SQL statement,
available as a DataTable object. The DataTable object is an object that the GridView (and indeed all
data controls) can bind to. If you go back and look at the source that has been created, you can see the
source for the two controls you added to your form.
<div>
OldValuesParameterFormatString=”original_{0}”
SelectMethod=”GetPlayers” TypeName=”odsTableAdapters.PlayersTableAdapter”>
</asp:ObjectDataSource>
</div>
DataKeyNames=”PlayerID”
DataSourceID=”ObjectDataSource1”>
<Columns>
InsertVisible=”False”
ReadOnly=”True” SortExpression=”PlayerID” />
SortExpression=”FirstName” />
SortExpression=”LastName” />

SortExpression=”Position” />
SortExpression=”DateJoined” />
SortExpression=”DateLeft” />
</Columns>
</asp:GridView>

The GridView control binds each of the fields in the dataset to a column in a table on the display.
The ObjectDataSource takes five attributes. The ID and runat attributes are standard, the
OldValuesParameterFormatString is set to the original setting, the SelectMethod attribute specifies
the name of the actual method, and the TypeName specifies the PlayersTableAdapter. These are all the
instructions needed to be able to bind the return PlayersTable to the GridView control. The final display
looks the same as a normal GridView control — it’s only the plumbing underneath that has routed your
data from the ObjectDataSource control that is different.

The Wrox United ObjectDataSource
This data so far has been static. So as mentioned previously, in this next Try It Out, you go one further
and use the ObjectDataSource control to be able to edit and update your squad’s details. In the Admin
section of the Wrox United site, there is a page called EditSquad.aspx, which is used to change the
players’ details. However, it uses the SqlDataSource control for the details. This can be replaced with
an ObjectDataSource control. It has insert, update, select, and delete methods that map neatly to the
methods in a simple class.

364


Componentization
Try It Out
The Wrox United ObjectDataSource

1. Open the Wrox United application from the chapter samples (C:\BegASPNET2\Chapters\
Begin\Chapter10\WroxUnited) in Visual Web Developer.

2.
3.
4.
5.

Right-click the App_Code folder and select Add New Item from the list.

6.

When you get the page where you can choose to use SQL statements or stored procedures.
select the Use SQL statements radio button and click Next.

7.

On the next wizard screen, you can define the SQL statement. Type the following SQL statement
into the “What data should be loaded into the table” area of the dialog box:

From the Visual Studio installed templates, click DataSet.
Rename the DataSet wroxunited.xsd and click Add.
VWD starts the TableAdapter Configuration Wizard. (As before, be patient here.) When the
wizard finally arrives, select wroxunited (Web.config) and click Next.

SELECT PlayerID, FirstName, LastName, Position, PictureURL, DateJoined, DateLeft
FROM Players
WHERE PlayerID = @PlayerID

8.


After entering the SQL statement, click Next. You can now define which methods the component will expose. Uncheck the Fill a DataTable check box and make sure that Return a DataTable
check box is checked. In the Method name box, type GetPlayers. This method is used later to
retrieve the data. Make sure the final check box, “Create methods to send update directly to the
database,” is checked.

9.
10.
11.
12.

Click Next and then click Finish. Save the data component, and close the component designer.

13.

From the Data Section of the Toolbox, drag an ObjectDataSource control where the
SqlDataSource used to be.

14.

Click the black arrow at the top right of the ObjectDataSource control, and from the Common
Tasks menu, select Configure Data Source.

15.

In the opening dialog box, select wroxunitedTableAdapters.PlayersTableAdapter and
click Next.

16.


In the Select tab, select the GetPlayers(Int32 PlayerID), returns PlayersDataTable
method from the drop-down list box and click Next.

17.

In the Define Parameters dialog box, select Control from the Parameter Source drop-down list
box. Select GridView1 in Control view. The parameters on the left of the dialog box will now
show GridView.SelectedValue. Click Finish.

Select Build➪Build Web Site to compile the component.
Open the Admin folder of WroxUnited and open the EditSquad.aspx file.
In Design View, scroll down, select the second SqlDataSource control, DetailsDataSource
(shown in Figure 10-15), and delete it.

365


Chapter 10

Figure 10-15

18.
19.
20.

Right-click the ObjectDataSource control in Design View and select Properties.
In the Properties window, change the (ID) property so that it reads “DetailsDataSource”.
Open EditSquad.aspx.cs and amend the code in the procedure parameters to read as follows
in the three subs:


protected void DetailsDataSource_Updated(object sender ,
System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs
{
...
}
protected void DetailsDataSource_Inserted(object sender ,
System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs
...
}
protected void DetailsDataSource_Deleting(object sender ,
System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs
{
...
}

366

e)

e)

As
e)


Componentization
21.
22.

Save and close the file.

Run the application, log in as an administrator (dave\dave@123), and navigate to the
EditSquad.aspx page. It works in the same way as before except that you are now using an
ObjectDataSource control.

How It Works
You haven’t changed much between this and the previous example. You built a data component, and
you then added an ObjectDataSource control into the EditSquad.aspx page. You added methods for
the Update, Insert, and Delete methods via the wizard. The code that provided your functionality in the
classes was already in existence — all you had to do was change the references from the SqlDataSource
control to the ObjectDataSource control. Then you ran it, and the WroxUnited application was able to
use the ObjectDataSource instead.

User Controls
Your final problem is that of making your code easy to reuse, and this is addressed by user controls.
Again, these existed in ASP.NET 1.x, but this is something that also has been improved upon in ASP.NET
2.0. So what are user controls? Well in a nutshell, user controls are reusable Web Forms. They’ve been
through several name changes and evolutions from scriptlets to pagelets, before arriving at user controls. They can be thought of as mini-scripts, mini-pages, or pages within your pages, but however you
choose to think of them, the key is that they can be called up as many times as you need them.
If you browse the Wrox United site, you can see several examples of user controls, and one, the News
control, is visible on the front page. In fact, if you look at the front page (shown in Figure 10-16), it is a
multitude of components garnered from different sources.
The News control is a user control, the Login control is an ASP.NET control, the shopping cart is a link to
a user control, and the menu is derived from the site master, which itself is an ASP.NET control. So the
entire site front page and design is reusable. If you click the Shopping Cart link, you will see the second
user control, shown in Figure 10-17.
And there are a couple more user controls in the administrative section of the site too, but you get the
idea that these controls can be used in multiple pages, or called from different places, and rather than
having to cut and paste the code individually each time, you can just call on this one section of code over
and over again. One question you might have is how do they differ from the normal ASP.NET server
controls, such as the TextBox control or the Login control that you looked at earlier?

Very little is the answer. The main difference is that you have to provide the code behind the control
yourself, whereas ASP.NET server controls come fully functional out of the box. You can add properties
to user controls and set them as attributes, just like you would with a normal ASP.NET server control.

367


Chapter 10
Login Control (ASP.NET)

Link to ShoppingCart Control (User)
Figure 10-16

News Control (User)

So why isn’t everything an ASP.NET server control? Well, ASP.NET 2.0 ships with a multitude of controls designed for the most common scenarios and situations. ASP.NET 2.0 adds greatly to the number of
server controls. For example, in ASP.NET 1.1 if you wanted a Login control, you had to stitch together a
username text box, a password text box, a button, and a label for messages within a panel, so you had to
create this as a user control. In version 2.0, the Login control comes as a server control. However, it just
isn’t possible to anticipate everything that a user might want or need. Therefore, it makes sense to have
the flexibility to create your own.
If you view the source code in Internet Explorer for the home page (Default.aspx) in WroxUnited.net,
you’ll see no indication that a user control has been used — it’s all HTML elements and some occasional
script, which is just as it should be. If you were using a Flash plug-in or a Java applet, you would see
some indication with an <object> tag or on older browsers, possibly an <embed> tag. So there’s no
worry about extra download time being taken either.

368



Componentization

Figure 10-17

If you look at the actual page that is sent to the server, you can see the user control is included with two
simple lines of code that highlighted here (this source code page is available for download at
www.wrox.com):
<%@ Page Language=”C#” Trace=”false” MasterPageFile=”~/site.master”
AutoEventWireup=”true” codefile=”Default.aspx.cs” Inherits=”_Default” %>
<%@ Register TagPrefix=”uc1” TagName=”News” Src=”News.ascx” %>
<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”server”>

Welcome to the Wrox United Web site.


We’re a great football team. No really, we are. Don’t take any notice
of our past performance. We’re just unlucky.


<uc1:news id=”News1” runat=”server” ItemsToShow=”3”></uc1:news>
</asp:Content>

This page starts giving you some clues as to how user controls work.

User Control Structure
User controls are stored in separate files with a separate .ascx extension. Any time you see this extension,
you know that you are dealing with a user control. To create a user control, you need to add a @Register
directive to the top of your Web Form identifying where you can find your user control:
<%@Register TagPrefix=”WroxUnited” TagName=”MyControl” %>

369


Chapter 10
You need to add a new tag specifying where the control will go on your page. It consists of the

TagPrefix, followed by a colon, followed by the TagName, an ID, and the now familiar runat=server
attribute:
<WroxUnited:MyControl id=”mycontrol1” runat=”server”>
</WroxUnited:MyControl>

Lastly, you need to specify the user control itself in a separate .ascx file. Unlike Web Forms, you don’t
need to specify extra <html> and <body> tags, because the contents of this control will be added to the
body of the containing main page. In fact, all you need to have is the controls that you want to include.
For example, you could include the controls from the code-behind example used earlier in the chapter:
of life, the universe and everything?:”></asp:Label>
<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox>



<asp:Button ID=”Button1” runat=”server” Text=”Submit” />


<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>

Of course, user controls can have code-behind files as well, just like Web Forms:
public void Page_Load( object sender, System.EventArgs e)
{
if (Page.IsPostBack)
{
if (TextBox1.Text == “42”)
Label2.Text = “So you read Douglas Adams as well...”;
else
{
Label2.Text = “No, I’m not sure that’s it”;

}
}

This control can then be bolted into your web pages wherever you specify the @Register directive and
add a tag for the control.

A Simple User Control
In the next Try It Out, you’re going to start by creating a trivial “Hello World”-style user control to get
you used to the idea of including them in your pages. This code does no more than encapsulate the
code-behind from the first example you created in the chapter as a user control. You’ll see how you can
place the user control in one web page, and then in a second web page.

Try It Out
Creating a Simple User Control
1. Open VWD and create a new ASP.NET web site called SimpleUserControl in the chapter directory (C:\BegASPNET\Chapters\Begin\Chapter10).

2.

370

In Solution Explorer, right-click the web site and select Add New Item. Select Web User Control,
enter the name SimpleUserControl.ascx, and check the Place Code in Separate File option, as
shown in Figure 10-18.


Componentization

Figure 10-18

3.


Now you need to add the controls to the page. Again, drag two Label controls, a TextBox control, and a Button control, as shown in Figure 10-19.

Figure 10-19

371


Chapter 10
You can cut and paste the relevant code from the first Try It Out in this chapter into Source View
if you still have it at hand:
life, the universe and everything?:”></asp:Label>
<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox>



<asp:Button ID=”Button1” runat=”server” Text=”Submit” />


<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>

4.

Double-click the page again and this time, add the following code-behind to
SimpleUserControl.ascx.cs:

public partial class SimpleUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)

{
if (Page.IsPostBack)
{
if (TextBox1.Text == “42”)
Label2.Text = “So you read Douglas Adams as well...”;
else
{
Label2.Text = “No, I’m not sure that’s it”;
}
}
}
}

5.
6.

Click the green arrow to run Default.aspx. It works in exactly as it did in the first Try It Out of
this chapter, as evidenced in Figure 10-21.

7.

Go to Solution Explorer and right-click the project. Select Add New Item and add a new Web
Form to the page called secondpage.aspx.

8.

372

Next you need to add this control to a page. From Solution Explorer, drag
SimpleControlUser.ascx into Design View for Default.aspx (see Figure 10-20).


Go to Design View and drag SimpleUserControl.ascx into this page. Next, go to Solution
Explorer and right-click secondpage.aspx and select Set As Start Page.


Componentization

Figure 10-20

Figure 10-21

9.

Run the project again. You should see what appears in Figure 10-22. Your control has been successfully duplicated with no extra lines of code being required.

373


Chapter 10

Figure 10-22

How It Works
This hopefully shows you just how easy it is to reuse code in your pages. If you go to Default.aspx
and view the source, you will see the following:
<%@ Page Language=”C#” AutoEventWireup=”false” CodeFile=”Default.aspx.cs”
Inherits=”_Default” %>
<% Register Src=”SimpleUserControl.ascx” TagPrefix=”uc1”
TagName=”SimpleUserControl” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “ />DTD/xhtml11.dtd”>

<html xmlns=” >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<uc1:SimpleUserControl id=”SimpleUserControl1 runat=”server” />
</div>
</form>
</body>
</html>

The highlighted lines of code are the only two lines that have been added to the original source code.
The first registers the user control and specifies a tag prefix of uc1 (short for “user control one”) and a
TagName of SimpleUserControl. The control is then inserted into the page along with an id attribute
and a runat=server attribute.
There’s nothing to stop you from copying this tag and pasting it again and again in the page, although it
might make your page a little illogical, with several versions of the user control. Note that this example
got you to cut and paste the old code from the code-behind page. This was quite deliberate because this
was the old way of transferring replicated code. Each time you wanted to transfer the code, you would
cut and paste it manually. Not only is cutting and pasting more labor-intensive, but it is also far more
prone to mistakes, because if you altered the code in one page, it would need to be altered in all of the
rest. With user controls, any changes you need to make can just be made to the .ascx file and the .ascx.cs
file themselves, and then every time the user control is called, it automatically uses the new code.

374


Componentization


The Wrox United News User Control
You’re now going to move onto a more complex user control, and one that is used on the Wrox United
web site. You’re going to re-create the News control that you find on the main Wrox United site. This control scans the News table, selects the most up-to-date stories, and displays them on the front page, with
the most recent being displayed first.
Before you launch into the coding, it’s worth saying a little bit about why we chose to make this a user
control, while other bits and pieces we chose not to. A News control is something that is going to be common on many web sites (although technically speaking, user controls shouldn’t be used across several
applications — as you will see at the end of this chapter — because there is something better served for
that purpose). It is also something that will quite likely be called upon at several places throughout the
application (although you only call upon it once within the Wrox United application), and the principle
will remain the same throughout — it will display a list of articles in order, with the most recent first. Of
course, not all things you will design on this site will be suitable for reuse and for creating as user controls, but the News control is a content delivery mechanism and content is the driving force behind most
web sites. In the following Try It Out, you create your own News user control and drop it into your own
blank page.

Try It Out
Using the News Control
1. Open Visual Web Developer and select Open Web Site. From the Chapter10 folder (C:\BegASPNET\
Chapters\Begin\Chapter10), select WroxUnitedNewsControl and click OK.

2.

Go to Visual Web Developer and right-click the top item in Solution Explorer. Select Add New
Item and select Web User Control. Type NewsUserControl.ascx in the Name text box. Make
sure the Place Code in Separate File check box is selected, as shown in Figure 10-23.

Figure 10-23

3.


Go to Design View and drag a SqlDataSource control from the Data section of the Toolbox
menu. Don’t, however, click to configure the Data Source from the Common Tasks box that
appears.

375


Chapter 10
4.

From the Data section of the Toolbox menu, add a Repeater control below the SqlDataSource
and select SqlDataSource1 to be the Repeater’s Data Source (see Figure 10-24).

Figure 10-24

5.

Add the template to the HTML. With the Repeater control, you have to switch to Source View
to add the template. Switch to Source View and add the following code:

<asp:Repeater ID=”Repeater1” Runat=”server” DataSourceID=”SqlDataSource1”>
<ItemTemplate>
<div class=”newsItem”>
<span class=”newsDate”><%#Eval(“DateToShow”, “{0:dd MMM yyyy}”)%>
</span>
<span class=”newsTitle”><%#Eval(“Title”)%></span>
</div>
<span class=”newsContent”>
<%#Eval(“Description”) %>
</span>

</ItemTemplate>
</asp:Repeater>

6.

Still in Source View, add the following to the SqlDataSource:

ConnectionString=”<%$ConnectionStrings:WroxUnited%>”

This contains the connection string information that you will need for this example.

7.
376

Go to the code-behind file and add the following code for an ItemsToShow property, which
governs how many items are shown on the screen at the same time:


Componentization
public partial class NewsUserControl : System.Web.UI.UserControl
{
private int _itemsToShow = 5;
public int ItemsToShow
{
get
{
return _itemsToShow;
}
set
{

_itemsToShow = value;
}
}

8.

Add the following code directly underneath the code you previously added:

private void Page_PreRender(object sender, System.EventArgs e)
{
string sel
= string.Format(“SELECT Top {0} * FROM [News] WHERE DateToShow
<= ‘{1}’ ORDER BY DateToShow DESC”, _itemsToShow,
DateTime.Now.ToString(“yyyy/MM/dd”));
//Make sure above is all on one line.
SqlDataSource1.SelectCommand = sel;
}

9.
10.

Go to Solution Explorer and create a new Web Form called NewsDisplay.aspx. Go to Design
View and drag your NewsUserControl.ascx into the Web Form.
Run it — it’s fairly raw without any styles, but you will see five news items, as shown in
Figure 10-25.

Figure 10-25

377



×