All you need is data from the Teamstable, soselect the Teamstable, then select each field from that table, as shown in Figure 10-16: In this book, the examples use the Access version of
Trang 2text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>'
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>'id="TeamNameLink" style="color:darkred" runat="server" />
Trang 3each of the teams In addition, you'll need to grab data from the Notesfield that describes each
of the teams Both of these tasks will be carried out next
5. The first step is to add some data source information to the page We're going to use the neatdata wizard feature of Web Matrix to generate some database access code In Codeview, drag aSELECTData Methodwizard onto the page from the Code Wizardspanel on the left, which shows
If you are using Microsoft Access, ensure that a copy of the database is placed into
the BegASPNET11\WroxUnited\Database folder (you need to create this folder if it
doesn't already exist)
Trang 4Figure 10-14
Figure 10-15
Now that you have a connection to your database, you can go ahead with the Code Wizard
7. Click Next, and the Code Wizard is launched All you need is data from the Teamstable, soselect the Teamstable, then select each field from that table, as shown in Figure 10-16:
In this book, the examples use the Access version of the database, but you can
obviously use the SQL Server version In fact, in Appendix D, a SQL Server
connection has been used instead.
Trang 6"[Teams].[Notes] FROM [Teams]";
System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();dbCommand.CommandText = queryString;
10. Create a new web.configfile for your Wrox United application and in the code that is
generated, add the highlighted line of code
Due to page width limitations, the highlighted line in the following code snippet has been wrapped to two lines You must ensure that the following statement is not
wrapped in your code and is all on one line!
Trang 8The ItemTemplatesection is used to display each row of data retrieved and gives you the option ofadding some layout and styling code:
<asp:DataList id="TeamList" runat="server">
<ItemTemplate>
<asp:linkbutton
text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>' id="TeamNameLink" style="color:darkred" runat="server" />
The Textproperty is set to display the value stored in the TeamNamefield for each row in the database.The CommandArgumentproperty stores the TeamIDthat represents the currently selected team Thisproperty will be very useful later on when we use the LinkButtoncontrol to display more information
on the page Later in this chapter, we'll use it to retrieve a list of players that play for the selected team.Now, let's look at the Labelcontrol:
<asp:Label text='<%# DataBinder.Eval(Container.DataItem, "Notes") %>' id="teamnotes" runat="server" />
Trang 9This control is a little simpler than the LinkButtoncontrol The interesting bit is the Textproperty that
is set to the value stored in the database for the notes for the currently selected team
Each of these controls will be rendered once for each row in the database Six teams would result in sixlinks and six notes Each result will have the same separator between items
The code used to access the data stored on the database should be familiar to you from working through
the exercises in Chapters 8 and 9 The Web Matrix data wizard takes a lot of hard work away and
produces neat functions that you can use in your code However, the Web Matrix wizards don't allowyou to specify a centralized database connection string, so we added a line to the default web.configfile created for this exercise:
Linking to the Teams.aspx Page
Before you finish this example completely, flip back to Default.aspxand change the following line ofcode as shown:
<asp:HyperLink id="lnkTeams" runat="server" NavigateUrl="Teams.aspx">
Data Rendering Controls
These controls are extremely feature-rich (they have numerous properties to choose from) and greatlysimplify the work of displaying a variety of data, particularly database-related data The definition of
Trang 10data in the context of these controls is very broad It could include database records, an ArrayList, anXML data source, or even custom collection of objects containing custom class instances There are twoimportant concepts you need to know:
❑ Data binding: This is the term used to describe the process of associating a server control withinformation in a data store Binding data to a server control is a two-step process in ASP.NET –first assign the server control's DataSourceproperty to the data you want to bind to and thencall the control's DataBind()method Controls can be bound to a variety of data sources,ranging from tables retrieved from the database to values stored in an object, such as an Array
or a Hashtable
❑ Templates: These are used to define the various layout elements of a particular control
Templates describe how data is displayed in the browser
The following table lists the available data controls:
The DataGrid Control
The DataGridcontrol provides a wealth of functionality for displaying data in columns and rows andhas many properties that you can use to control the layout of your grid For example, you could
alternate the colors for the rows of data being displayed Some useful properties for the DataGridcontrol include:
❑ AllowSorting: Allows you to dynamically sort and re-display the data based on the values in aselected column For example, if you have a table in a database containing employees' surnamesand salaries, enabling sorting would allow you to sort the rows in your table according to eithercolumn
Control Purpose
DataGrid Creates a multi-column, data-bound grid This control allows you to define
various types of columns, lay out the contents of the grid, and add specific functionality (edit button columns, hyperlink columns, and so on)
DataList Displays items from a data source by using templates and renders them as a
structured table You can customize the appearance and contents of the control by manipulating the templates that make up its different components Repeater TheRepeater control is very similar to the DataList, except that results are
not rendered in a table Each row in the data source is rendered in a format that you specify in the ItemTemplate Given the lack of structure in the rendered output, you may find that you use the ItemSeparatorTemplatemore often Unlike DataList, the Repeater control does not have any built-
in selection or editing support
Trang 11❑ AllowPaging: Allows you to view subsets of the data called by the DataGridcontrol ondifferent pages The number of items displayed on the page is determined by the PageSizeproperty.
❑ AlternatingItemStyle: Sets the style (such as background color) of every other item listed
❑ ItemStyle: The style of individual items If no AlternatingItemStyleis defined, all theitems will render with this style
❑ FooterStyle: The style of the footer (if any) at the end of the list
❑ HeaderStyle: The style of the header (if any) at the beginning of the list
To use the DataGridcontrol, declare it like the other server controls you've seen (using the
<asp:DataGrid>start and end tags), set the relevant properties, define the columns in your table, andthen apply the relevant template for those columns Within the template tags, include the information towhich the template must be applied:
The DataList Control
The DataListcontrol used in the previous example is useful for displaying rows of database
information (which can become columns in DataGridtables) in a format that you can control using
templates and styles Manipulating various template controls changes the way your data is presented The
DataListcontrol enables you to select and edit the data that is presented Here is a list of the supportedtemplates:
Trang 12You can actually make a DataList render like a DataGrid by arranging data in columns You can do this by changing the RepeatDirection property from Vertical to Horizontal We recommend trying this out yourself and taking a look at the source for the rendered page – you'll soon see where you need to add or remove layout data to customize the appearance of your data.
The Repeater Control
The Repeatercontrol is very similar to the DataListcontrol with one very important distinction: the
data displayed is always read-only You cannot edit the data being presented It is particularly useful for
displaying repeating rows of data Like the DataGridand DataListcontrols, it utilizes templates torender its various sections The templates it uses are generally the same as the ones used with theDataListcontrol, with a similar syntax The next Try-It-Out illustrates the Repeatercontrol in action.We've completed the first part of the Teams page, but it would be really useful to see the players on eachteam For that part of the example, we'll work with some more Web controls (including a Repeatercontrol) that bind to data
Try It Out Wrox United – Teams.aspx, Part 2
In this example, we'll make the TeamNamesfrom the previous example "clickable", so that when a team
is selected, the players of that team are listed on the right-hand side of the table
ItemTemplate This is a required template that provides the content and
layout for items referenced by DataList.AlternatingItemTemplate If defined, this template provides the content and layout for
alternating items in the DataList If it is not defined, ItemTemplate is used
EditItemTemplate If defined, this template provides editing controls, such as
text boxes, for items set to 'edit' in the DataList If it is not defined, ItemTemplate is used
FooterTemplate If defined, the FooterTemplate provides the content and
layout for the footer section of the DataList If it is not defined, the footer section will not be displayed
HeaderTemplate If defined, this provides the content and layout for the
header section of the DataList If it is not defined, the header section will not be displayed
SelectedItemTemplate If defined, this template provides the content and layout for
the currently selected item in the DataList If it is not defined, ItemTemplate is used
SeparatorTemplate If defined, this provides the content and layout for the
separator between items in the DataList If it is not defined,
a separator will not be displayed
Trang 131. Reopen Teams.aspx, and go straight to Codeview We need to get some more data from thedatabase Start by dragging another SELECTquery onto the page and launching the wizard.
2. This time, select PlayerNamefrom the Playerstable and PositionNamefrom the Positionstable as the two columns to be displayed, as shown in Figure 10-20:
Figure 10-20
3. Before you can exit the wizard, you need to add some WHEREclause data to link the data thatyou're gathering This data comes from two different tables, Playersand Positions You alsoneed to ensure that player data is only retrieved for the specific team that you're interested in
4. Click the WHEREbutton to start adding a WHEREclause, which selects only those rows wherethe PlayerIDcolumn in the PlayerTeamjoin table matches the PlayerIDcolumn in thePlayerstable as shown in Figure 10-21:
Figure 10-21
Trang 145. Repeat this process to join the following sets of tables and columns: the Positioncolumn in thePlayerTeamtable to the PositionIDcolumn in the Positionstable, and the TeamIDcolumn
in the PlayerTeamtable to the TeamIDcolumn in the Teamstable
6. Finally, set the TeamIDcolumn in the PlayerTeamtable to be equal to the TeamIDparameter, asshown in Figure 10-22 This will be passed in when the function is called:
Figure 10-22
You should now see the screen shown in Figure 10-23:
Figure 10-23
Trang 157. Click Nextto test the query When prompted, enter an integer that corresponds to a validTeamID, as shown in Figure 10-24 (1 is a safe bet!):
to make it easier to read):
System.Data.IDataReader GetPlayersByTeam(int teamID)
{
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; " +
"Data Source=C:\\BegASPNET11\\WroxUnited\\Database\\WroxUnited.mdb";System.Data.IDbConnection dbConnection =
new System.Data.OleDb.OleDbConnection(connectionString);
string queryString =
"SELECT [Players].[PlayerName], [Positions].[PositionName] " +
"FROM [Players], [Positions], [PlayerTeam], [Teams] "+
Trang 16"WHERE (([PlayerTeam].[PlayerID] = [Players].[PlayerID]) " +
"AND ([PlayerTeam].[Position] = [Positions].[PositionID]) " +
"AND ([PlayerTeam].[TeamID] = [Teams].[TeamID]) " +
"AND ([PlayerTeam].[TeamID] = @TeamID))";
System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();dbCommand.CommandText = queryString;
Now, add some controls that can use this code Switch back to HTMLview and add another cell
to the table that contains a Repeatercontrol:
Trang 179. Head back to the DataListcontrol and edit the LinkButtoncontrol as follows:
<asp:linkbutton
text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>'
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>' id="TeamNameLink" style="color:darkred"
CommandName="ShowTeam" runat="server" />
10. Add the following to the DataListcontrol tag:
<asp:DataList id="TeamList" runat="server"
OnItemCommand="TeamList_ItemCommand">
11. Add the following line of code outside all the methods in the page (this is a public variable):string selectedTeam;
12. Finally, add the following code in the Codeview of the page:
void TeamList_ItemCommand(object sender, DataListCommandEventArgs e)
Trang 18Figure 10-26
How It Works
We extended the first part of the example to incorporate an event handler that runs some specific codewhen the name of a team is clicked This code is used to populate the Repeatercontrol Let's runthrough it bit-by-bit:
<asp:DataList id="TeamList" runat="server"
OnItemCommand="TeamList_ItemCommand">
Adding the OnItemCommandproperty to the DataListcontrol ensures that when the LinkButtonwithin the DataListis clicked, the ItemCommandevent of the Repeateris raised and code in theTeamList_ItemCommand()event handler is run However, we need to pass the CommandArgumentofthe LinkButton, so we assign a CommandNameproperty to the LinkButton:
<asp:linkbutton
text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>' id="TeamNameLink" style="color:darkred"
CommandName="ShowTeam" runat="server" />
In the event handler that runs when the ItemCommandevent is fired, we can use the CommandArgumentproperty of the LinkButton:
void TeamList_ItemCommand(object sender, DataListCommandEventArgs e)
The event handler takes two parameters eis an object of the type DataListCommandEventArgs Thismeans that we can access certain properties of ein our code that relate back to the control that originallyfired the event
Trang 19First, we can use the CommandNameproperty of the LinkButtonthat was set to ShowTeamearlier:
if (e.CommandName == "ShowTeam")
{
We test whether the argument passed into the event handler has a CommandNameset to ShowTeam If itdoes, we process some more code The next two lines extract the name of the currently selected team.This is used to set the value of the public string variable selectedTeam:
LinkButton button = (LinkButton)e.CommandSource;
selectedTeam = button.Text;
Notice that we first have to create a new LinkButton object and use it to work with the properties of thebutton that originally fired the method We can identify the button that the request originated from byusing the CommandSourceproperty of the EventArgs(e) passed into the method Once we have thenewly-created button object, we can access its Textproperty
The next section binds data to the PlayersList Repeatercontrol Here, we access the
CommandArgumentproperty of the eobject, which is the CommandArgumentproperty of the
LinkButtoncontrol that raised the event and is passed into the event handler Because this argument ispassed across as a string and we require an integer, we must first specify that the argument is a stringand then convert it to an integer:
This event handler is quite complicated, but is a great example of how to handle
events raised by child controls (the LinkButton ) via a parent control (the DataList ).
This is a process known as Event Bubbling, in which the events raised by the child
control bubble up to their parent control where they can be intercepted and handled.
Trang 20The data for the items in the Repeatercontrol comes from the GetPlayersByTeam()method:
System.Data.IDataReader GetPlayersByTeam(int teamID)
"SELECT [Players].[PlayerName], [Positions].[PositionName] " +
"FROM [Players], [Positions], [PlayerTeam], [Teams] "+
"WHERE (([PlayerTeam].[PlayerID] = [Players].[PlayerID]) " +
"AND ([PlayerTeam].[Position] = [Positions].[PositionID]) " +
"AND ([PlayerTeam].[TeamID] = [Teams].[TeamID]) " +
"AND ([PlayerTeam].[TeamID] = @TeamID))";
This query is followed by some code that creates a Commandobject, and a parameter that passes theTeamID
System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();dbCommand.CommandText = queryString;
Using a parameter ensures that the data passed into the method doesn't violate any
database constraints For example, using a parameter removes our obligation to
escape text that would be invalid in a SQL statement, worry about inserting dates in
an unsuitable format, and so on Catching data type errors in code before data is
passed to the database is a good way to work.
Trang 21Finally, the data is read from the database and the DataReaderobject is returned by the function:dbConnection.Open();
The only functionality difference between the two is that the DataListcan be used to edit data, whereasthe Repeateris always read-only For more information and some great examples, refer to Professional
ASP.NET 1.0, Special Edition, Wrox Press, ISBN 0-7645-4396-2.
Data-oriented controls have many different properties and events that we could discuss in depth here,
but it's time to move on and look at other topics I highly recommend that you play and experiment with these controls Check out the rendered HTML in your browser using View | Source – you'll find that
it's a great way to understand how the rendering process works, and how you can optimize your code to work with, not against, the ASP.NET compiler to produce the results you want.
You've now gained some experience of using a DataList, a Repeater, and a LinkButtonwhile puttingtogether one of the pages in the site As you saw at the end of the previous example, the DataList
control is a data rendering control The LinkButtoncontrol, however, is a rich control Let's find out moreabout this type of control
Rich Controls
Rich controls are compound in nature and provide extended functionality In other words, rich controls
are typically combinations of two or more simple or intrinsic controls that compose a single functional
unit, for example, an AdRotatorcontrol Another distinguishing trait of these controls is that they don'thave a direct correlation to any single HTML control, even though they render to HTML when displayed
in the client browser The following table discusses various rich controls and their functions:
Trang 22The nice thing about this family of rich controls is that they are just as easy to use as the other ASP.NETserver controls They may boast of more features and properties, but the basic way of defining them andinteracting with them is programmatically the same as for all the other ASP.NET server controls.
The Calendar Control
The Calendarcontrol produces some really complex HTML when rendered, but you'll find that addingthis control to a Web page is as simple as adding any other Web control! This control is designed topresent date information in the form of a calendar and allows a user to select a particular date You canconfigure the control via the SelectionModeproperty to allow the user to select a range of dates Youcan also completely customize how this control is presented using the many different properties that ithas access to Let's take a quick look at some of these properties:
FirstDayOfWeek=[Default|Monday|Tuesday|Wednesday|
Thursday|Friday|Saturday|Sunday]
The FirstDayOfWeekproperty enables you to choose the day of the week your calendar starts from.Some calendars default to Sunday as the first day of the week For business purposes, however, it's morepractical to have the week starting from Monday
AdRotator Displays advertisement banners on a Web form The displayed
advertisement is randomly changed each time the form is loaded or refreshed
Calendar Displays a one-month calendar for viewing/selecting a date, month, or
year
CheckBoxList Multiple-selection checkbox group; can be dynamically generated with
data binding
ImageButton Provides a clickable image with (optional) access to the clicked
coordinates to support image-map functionality
LinkButton Hyperlink-style button that posts back to the page of origin We've seen
a couple of these in action already
RadioButtonList Mutually exclusive radio button group Can be dynamically generated
with data binding
Trang 23The Calendarcontrol's SelectMonthTextand SelectWeekTextproperties enable you to customizethe HTML that is rendered at the browser – use these properties if you're really going for a customizedlook:
SelectMonthText="HTML text"
SelectWeekText="HTML text"
You need not define all of the properties of the ASP.NET Calendarcontrol to display the control In fact,the following declaration will create an efficient ASP.NET Calendarserver control that looks good anddisplays quite well:
<asp:Calendar id="MyCalendarControl" runat="server" />
When delivered to the client browser, the result is an HTML calendar as shown in Figure 10-27 thatenables you to navigate through the various days, months, and years:
Try It Out Wrox United – Default.aspx, Part 2, the Event Calendar
1. Reopen Default.aspxand add the following HTML table in the HTMLview to change thelayout of the new and improved front page:
<p>
Welcome to the Wrox United Website! Please select one
Trang 24<td style="VERTICAL-ALIGN: top; width: 350px;"> </td>
<td style="VERTICAL-ALIGN: top; width: 250px;"></td>
Trang 25Figure 10-28
3. Click the lightning bolt in the Propertiespane to display the available events, and double-click
on the DayRender()event's textbox to be taken back to Codeview, where you need to entermore code Before filling in the DayRender()event handler, let's take a moment to considerwhat we're trying to achieve We want to highlight the days of the games and store dates of thegames in the Gamestable in the database If we want to display more information about aparticular day, we also need to store the GameIDso that we can again query the database later
4. The next task is to add another DataReaderto this page using the wizard, and then store that
data in a Hashtable (where we can store details of dates and games in key-value pairs, as we saw
in Chapter 8) At the top of the page, add the following line of code:
System.Collections.Hashtable DateList;
5. Drag a SELECTdata wizard onto the page Select the GameIDand Datefields from the Gamestable, save this function with the name Dates(), and specify that it returns a DataReaderobject:
System.Data.IDataReader Dates()
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
Trang 26"Ole DB Services=-4; Data Source=C:\\BegASPNET11\\" +
7. Add a Page_Load()event handler to the page, just below the hashtable declaration:
public void Page_Load(object sender, EventArgs e)
{
DateList = new System.Collections.Hashtable();
// we need to run this each time the page is loaded, so that
// after a date is selected and the page is posted back, the
// active dates will still be highlighted
System.Data.IDataReader DateReader = Dates();
Trang 27e.Cell.Style.Add("border", "3 dotted darkred");
First, we added a Calendarcontrol to our page by simply dragging it onto the page and then wired it
up to an event handler:
<asp:Calendar id="EventCalendar" runat="server"
OnDayRender="EventCalendar_DayRender"></asp:Calendar>
Trang 28The OnDayRenderproperty ensures that when each day is rendered in the calendar, the event handler isfired This means that we can test each date as it is rendered, and compare it with the dates stored in thedatabase Let's take a look at the event handler:
public void EventCalendar_DayRender(object sender, DayRenderEventArgs e)
DateList = new System.Collections.Hashtable();
// we need to run this each time the page is loaded, so that
// after a date is selected and the page is posted back, the
// active dates will still be highlighted
System.Data.IDataReader DateReader = Dates();
The first part of the Page_Load()method is where we create a new DataReaderusing the Dates()function that is built using the wizard We can then loop through this data, and store key and value pairs
in the Hashtable In this case, we can store just the date information in both the key and the value parts
of the Hashtable:
while (DateReader.Read())
Trang 29The function that retrieves the data from the database is really quite simple and looks very similar to thecode we've seen previously – let's just recap the SQL that was generated to get the data we're interestedin:
string queryString = "SELECT [Games].[Date], [Games].[GameID] FROM [Games]";
In the final example of this chapter, we'll extend the calendar example so that the details of the match aredisplayed whenever the selected date corresponds to a match day
Try It Out Wrox United – Displaying Fixture Details
In this example, we need to respond to a different type of event to display the details of a match TheCalendarcontrol has many different events that can be handled, and the one we need to handle in thisexample is the SelectionChanged()event, which fires whenever a date is selected The user should beable to click on a highlighted date in the calendar and view the details of any matches scheduled for thatday Clicking on a different date will cause the SelectionChanged()event to fire, which we can handleand add code to display the data for the selected day
1. Let's start by adding some more controls to the page for displaying the results Start by adding aparagraph and an ASP.NET Panelcontrol Set the PanelID to pnlFixtureDetails, and itsVisibleproperty to false:
<asp:Calendar id="EventCalendar" runat="server"
2. Inside the Panelcontrol, add the following Repeatercontrol:
<asp:Repeater id="MatchesByDateList" runat="server">
Trang 30<span style="width:135px">
<%# Venue((string)DataBinder.Eval(Container.DataItem, "OpponentLocation"),
(int)DataBinder.Eval(Container.DataItem, "Location")) %>
</span><br />
Another piece of code needs to be added to render an appropriate value for the match venue
We'll add a venue function in just a moment, and we'll examine why we need this in the How It
4. Add the following event handler to the page:
public void EventCalendar_SelectionChanged(object sender, EventArgs e)
{
if (DateList[EventCalendar.SelectedDate] != null)
{
MatchesByDateList.DataSource = GamesByDate(EventCalendar.SelectedDate);pnlFixtureDetails.Visible = true;
MatchesByDateList.DataBind();
}
else
{
Trang 31pnlFixtureDetails.Visible = false;
}
}
5. Add the Venue()function:
public string Venue(string OpponentLocation, int MatchVenue)
6. Finally, we need to add a function that gets the data that we're interested in We need to display:
1. The name of the team (the TeamNamefield from the Teamstable)
2. The name of the opposing side (the OpponentNamefield from the Opponentstable)
3. The location of the game (the Locationfield from the Gamestable)
4. The home location of the opposing team (the OpponentLocationfrom the Opponentstable)
We also need to add some WHEREclauses to link together the related tables, so select the WHEREclause and add the following relationships:
1. OpponentIDfrom the Opponentstable is equal to the OpposingTeamfield in the Gamestable
2. TeamIDfrom the Teamstable is equal to the WroxTeamfield in the Gamestable
3. Datefrom the Gamestable is equal to a parameter that we input called @Date
Save the method as GamesByDate(), and have it return another DataReaderobject If it allgoes according to plan, you will end up with the following code:
System.Data.IDataReader GamesByDate(System.DateTime date)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB
Services=-4; Data Source=C:\\BegASPNET11\\" +
Trang 32"[Games].[Location], [Opponents].[OpponentLocation] " +
"FROM [Teams], [Opponents], [Games] " +
"WHERE (([Opponents].[OpponentID] = [Games].[OpposingTeam]) " +
"AND ([Teams].[TeamID] = [Games].[WroxTeam]) " +
"AND ([Games].[Date] = @Date))";
System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();dbCommand.CommandText = queryString;
7. Change this code to use the central connection string as follows:
System.Data.IDataReader GamesByDate1(System.DateTime date)
Trang 33Figure 10-30
How It Works
We've added another panel to the page to display details of matches on a specific day We first added thePanelcontrol itself, and then started to build up another Repeatercontrol:
<asp:Panel id="pnlFixtureDetails" runat="server" visible="false">
<asp:Repeater id="MatchesByDateList" runat="server">
Trang 34Notice how the text within the span contains a data binding expression that takes the TeamNamecolumnfrom the data source and places it as text within the control.
We repeat the process of building up the template for the rest of the columns:
<span style="width:110px">Opposing Team</span>
Finally, after finishing with the items in the Repeater, we add a SeparatorTemplate:
Let's head back to the Venue()function and look at how it works:
public string Venue(string OpponentLocation, int MatchVenue)
{
The function takes two input parameters – the location of the opposing team's pitch and the flag thatstates whether the match is at home or away It returns a string that writes out either the name of thehome pitch, or the name of the opposing teams pitch:
The rest of the code for this exercise deals with getting the match data from the database and displaying
it when an event happens We want to display details when the currently selected date in the calendarchanges, so we added an OnSelectionChangedattribute to the Calendarcontrol:
Trang 35Then we added the event handler code:
public void EventCalendar_SelectionChanged(object sender, EventArgs e)
{
if (DateList[EventCalendar.SelectedDate] != null)
{
MatchesByDateList.DataSource = GamesByDate(EventCalendar.SelectedDate);pnlFixtureDetails.Visible = true;
panel is data bound only if matches are scheduled for the selected date – if not, the panel is hidden.
The actual code that retrieved the data included quite a substantial SELECTquery:
string queryString =
"SELECT [Teams].[TeamName], [Opponents].[OpponentName], " +
"[Games].[Location], [Opponents].[OpponentLocation] " +
"FROM [Teams], [Opponents], [Games] " +
"WHERE (([Opponents].[OpponentID] = [Games].[OpposingTeam]) " +
"AND ([Teams].[TeamID] = [Games].[WroxTeam]) " +
"AND ([Games].[Date] = @Date))";
Because we are gathering data from multiple tables, the query used is a bit long-winded As the endresult, it retrieves the required data fields from three tables and displays them on the page There aretwo more types of controls that we need to look at in this chapter First, we're going to look at the Web-Matrix-specific controls, and produce another quick and simple ASP.NET page In the second example,we'll take a quick look at validation controls
Web Matrix Controls
There are some extra controls that you can use when working with Web Matrix to develop Web
applications They are designed to make life very simple when you want to create data-driven pages.The MX DataGrid
This control is a lot like a normal DataGridcontrol, except that you can use it in conjunction with a WebMatrix DataSourcecontrol There are two data source controls, one for SQL Server connections and onefor Access connections There is only one extra property on the MX DataGridcontrol – the
DataSourceControlIDproperty This is how you tell the MX grid to get its data from the appropriatedata source control
Trang 36The Data Source Controls
These controls have three simple properties:
❑ ConnectionString: The string for connecting to the database
❑ SelectCommand: The SQL used to get the data into the grid
❑ EnableViewState: To determine whether the data stored in the control has persisted betweenpostbacks
Let's see a quick example of this in action
Try It Out Wrox United – Players.aspx and the Web Matrix MX DataGrid
1. Create a new ASP.NET page and call it Players.aspx In the Designview, add a Heading 1thatdisplays the text Wrox United Underneath this, add a paragraph underneath a Heading 2thatdisplays the text Players On a new line, switch back to the Normalparagraph style Now we canadd some content Then in in the Workspace | Datapanel at the top left of the Web Matrixenvironment, switch to Dataview Now drag the Playerstable onto the form, below the twoheadings as shown in Figure 10-31:
Figure 10-31
Trang 37You can actually run the page at this stage – with one click and drag operation, you can display
an entire table of data on the screen If you run the page now, you will see the screen shown inFigure 10-32:
Figure 10-32
Although this is very cool, we don't necessarily want just anyone to view the site login orpassword details Also, a status flag of 1, 2, or 3doesn't mean much whereas Active, Injured, orRetiredwould mean more to visitors Let's amend the example slightly
3. Switch to Designview in Web Matrix, select the DataSourcecontrol, and in the Propertiespanelset the SelectCommandto the following:
SELECT PlayerID, PlayerName, Profile, JoinDate FROM [Players]
4. Select the MxDataGridcontrol and change the AutoGenerateFieldsproperty to false, thenback to trueto refresh the grid Run the page again to see the screen shown in Figure 10-33:
Trang 38Figure 10-33
How It Works
This simple example demonstrates how Web Matrix can make life easy for us! The results of this quickand simple page aren't exactly brilliant, but the information we want to display is on the form withminimal fuss The MxDataGridcontrol can be customized to a great extent like the.NET DataGridcontrol, so that you can better control how the data is rendered
Let's take a quick look at the code that was generated for us:
The first control added to the page was the DataSourceControlthat is either a
SQLDataSourceControlor an AccessDataSourceControl, depending on the database that you areusing This control contains a connection string, and a SELECTstatement to retrieve the data that we'reinterested in This control is accompanied by the MxDataGrid:
<wmx:MxDataGrid id="MxDataGrid1" runat="server" BorderStyle="None"
BorderWidth="1px" DataKeyField="PlayerID"
CellPadding="3" BackColor="White" AllowPaging="true"
DataMember="Players" AllowSorting="true"
BorderColor="#CCCCCC"
Trang 39<FooterStyle forecolor="#000066" backcolor="White"></FooterStyle>
<HeaderStyle font-bold="true" forecolor="White"
❑ DataKeyField: The unique identifier for each row in the table
❑ DataMember: The name of the table you want to view
❑ DataSourceControlID: The name of the control that contains the data
Also included in the default implementation of this grid is a considerable amount of styling informationthat you might want to remove When it comes to styling a site, it makes sense to remove this
information to ensure that all pages follow the same style sheet
To further improve this page, you could manually specify the columns that appear in the grid and addformatting information for the JoinDatefield For example, you might want to remove the time portion
<FooterStyle forecolor="#000066" backcolor="White"></FooterStyle>
<HeaderStyle font-bold="true" forecolor="White"
Trang 40This will change the appearance of the page as shown in Figure 10-34:
Figure 10-34
If you want to use the centralized connection string, you could alter the code as follows:
<wmx:AccessDataSourceControl id="AccessDataSourceControl1" runat="server" SelectCommand="SELECT PlayerID, PlayerName, Profile, JoinDate FROM [Players]"ConnectionString='<%# ConfigurationSettings.AppSettings("ConnectionString")%>'