Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 5 docx

90 318 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 5 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Figure 10-10 3. Drag a DataList control into the first cell of the table from the Web Controls panel on the left, as shown in Figure 10-11: Figure 10-11 4. Let's do some work on the code in the page. First, switch to HTML view and enter the following 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" /> <br /> <asp:Label text='<%# DataBinder.Eval(Container.DataItem, "Notes") %>' id="teamnotes" runat="server" /> </ItemTemplate> <SeparatorTemplate> <br /> <hr color="#b0c4de" width="200px"/> </SeparatorTemplate> </asp:DataList> We've entered some data binding expressions in here, but not yet created a data source for this control. Next, you'll need to grab the name of each of the teams from the database, and create an ID for each team. This ID will come in handy when you need to get more information about 333 ASP.NET Server Controls each of the teams. In addition, you'll need to grab data from the Notes field 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 neat data wizard feature of Web Matrix to generate some database access code. In Code view, drag a SELECT Data Method wizard onto the page from the Code Wizards panel on the left, which shows up as shown in Figure 10-12: Figure 10-12 6. Create a new database connection to the WroxUnited database by selecting your preferred database type, and clicking on the Create button. If you are using Access, you will be prompted to enter the path to the database. If you are using MSDE, you will be prompted to select the WroxUnited database from your database list; see Figures 10-13, 10-14, and 10-15: Figure 10-13 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). 334 Chapter 10 Figure 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 Teams table, so select the Teams table, 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. 335 ASP.NET Server Controls Figure 10-16 8. Click Next, and you can test out the query. You should see a screen similar to Figure 10-17: Figure 10-17 9. In the final screen, save this method as GetTeams(), ensure that the DataReader type is selected, and then click Finish, as shown in Figure 10-18: 336 Chapter 10 Figure 10-18 Back in Code view, you will now see the following: System.Data.IDataReader GetTeams() { 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 [Teams].[TeamID], [Teams].[TeamName], " + "[Teams].[Notes] FROM [Teams]"; System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand(); dbCommand.CommandText = queryString; dbCommand.Connection = dbConnection; dbConnection.Open(); System.Data.IDataReader dataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); return dataReader; } Phew – that's a lot of code! These code builders are very useful, and we'll be using these quite often as we build up the site. We now have a function that returns a DataReader object that we can use to populate the DataList control. However, before we continue, we need to change this code a bit. The database connection string can be stored in a central location in the web.config file. Since we'll be doing a fair amount of database work for this application, let's change the code so that we use this technique. 10. Create a new web.config file 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! 337 ASP.NET Server Controls <?xml version="1.0" encoding="UTF-8" ?> <configuration> <appSettings> <add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\BegASPNET11\WroxUnited\Database\WroxUnited.mdb"/> </appSettings> <system.web> 11. Modify the GetTeams() method as follows to make use of this global connection string: System.Data.IDataReader GetTeams() { string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; System.Data.IDbConnection dbConnection = new System.Data.OleDb.OleDbConnection(connectionString); 12. Add the following code block above the GetTeams() function: void Page_Load() { TeamList.DataSource = GetTeams(); TeamList.DataBind(); } That's it for this page. Run the page; the output is as shown to Figure 10-19: Figure 10-19 338 Chapter 10 How It Works This exercise used many different types of ASP.NET controls to display team information on the page. Let's look at each of these controls, in turn, starting with the DataList control. The DataList control is a powerful way to display repeated values from a database. It uses templates to present the data. In this example, we added content for the ItemTemplate and SeparatorTemplate elements within the DataList. The ItemTemplate section is used to display each row of data retrieved and gives you the option of adding 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" /> <br /> <asp:Label text='<%# DataBinder.Eval(Container.DataItem, "Notes") %>' id="teamnotes" runat="server" /> </ItemTemplate> The SeparatorTemplate is where we added a horizontal line to clearly separate the results: <SeparatorTemplate> <br /> <hr color="#b0c4de" width="200px"/> </SeparatorTemplate> </asp:DataList> Inside the ItemTemplate, we used two different controls – an ASP.NET LinkButton control and a Label control. Let's first look at the LinkButton control: <asp:linkbutton text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>' id="TeamNameLink" style="color:darkred" runat="server" /> The Text property is set to display the value stored in the TeamName field for each row in the database. The CommandArgument property stores the TeamID that represents the currently selected team. This property will be very useful later on when we use the LinkButton control 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 Label control: <asp:Label text='<%# DataBinder.Eval(Container.DataItem, "Notes") %>' id="teamnotes" runat="server" /> 339 ASP.NET Server Controls This control is a little simpler than the LinkButton control. The interesting bit is the Text property 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 six links 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 allow you to specify a centralized database connection string, so we added a line to the default web.config file created for this exercise: <add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\BegASPNET11\WroxUnited\Database\WroxUnited.mdb"/> Once this was added, the connectionString created by the data access wizard was changed as follows: string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; This line of code looks up the value stored in the central web.config file and uses that value to connect to the database. Linking to the Teams.aspx Page Before you finish this example completely, flip back to Default.aspx and change the following line of code as shown: <asp:HyperLink id="lnkTeams" runat="server" NavigateUrl="Teams.aspx"> Teams </asp:HyperLink> Changing the NavigateUrl property means that you can link to the newly created Teams.aspx page from the main front page. The DataList control is one of the numerous data controls available to ASP.NET developers. Here's a quick look at the other controls available to us. Data Rendering Controls These controls are extremely feature-rich (they have numerous properties to choose from) and greatly simplify the work of displaying a variety of data, particularly database-related data. The definition of 340 Chapter 10 data in the context of these controls is very broad. It could include database records, an ArrayList, an XML data source, or even custom collection of objects containing custom class instances. There are two important concepts you need to know: ❑ Data binding: This is the term used to describe the process of associating a server control with information in a data store. Binding data to a server control is a two-step process in ASP.NET – first assign the server control's DataSource property to the data you want to bind to and then call 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 DataGrid control provides a wealth of functionality for displaying data in columns and rows and has 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 DataGrid control include: ❑ AllowSorting: Allows you to dynamically sort and re-display the data based on the values in a selected column. For example, if you have a table in a database containing employees' surnames and salaries, enabling sorting would allow you to sort the rows in your table according to either column. 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 The Repeater 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 ItemSeparatorTemplate more often. Unlike DataList, the Repeater control does not have any built- in selection or editing support. 341 ASP.NET Server Controls [...]... binding The nice thing about this family of rich controls is that they are just as easy to use as the other ASP.NET server controls They may boast of more features and properties, but the basic way of defining them and interacting with them is programmatically the same as for all the other ASP.NET server controls The Calendar Control The Calendar control produces some really complex HTML when rendered,... style="width:110px;height:25px">Date: 360 ASP NET Server Controls Wrox Team Opposing Team ... declaration will create an efficient ASP.NET Calendar server control that looks good and displays quite well: When delivered to the client browser, the result is an HTML calendar as shown in Figure 10-27 that enables you to navigate through the various days, months, and years: Figure 10-27 Take a look at the HTML that ASP.NET produced to create this page... e.Cell.Style.Add("font-size", "larger"); 357 Chapter 10 e.Cell.Style.Add("border", "3 dotted darkred"); e.Cell.Style.Add("background", "#f0f0f0"); } else { e.Cell.Style.Add("font-weight", "lighter"); e.Cell.Style.Add("color", "DimGray"); } } 9 Run the page You should see the screen shown in Figure 10-29: Figure 10-29 How It Works The Calendar control is one of the most complex controls in the ASP.NET toolbox, and without writing... read-only For more information and some great examples, refer to Professional ASP.NET 1.0, Special Edition, Wrox Press, ISBN 0-76 45- 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... 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 LinkButton while putting together one of the pages in the site As you... called: Figure 10-22 You should now see the screen shown in Figure 10-23: Figure 10-23 3 45 Chapter 10 7 Click Next to test the query When prompted, enter an integer that corresponds to a valid TeamID, as shown in Figure 10-24 (1 is a safe bet!): Figure 10-24 You should now see the screen shown in Figure 10- 25: Figure 10- 25 8 Save the query as a DataReader called GetPlayersByTeam You can now exit the wizard... day, an entire week, or the entire month 353 Chapter 10 The Calendar control's SelectMonthText and SelectWeekText properties enable you to customize the HTML that is rendered at the browser – use these properties if you're really going for a customized look: SelectMonthText="HTML text" SelectWeekText="HTML text" You need not define all of the properties of the ASP.NET Calendar control to display the control... With this, you've got a Repeater control and a function to fill it with data However, a few things are missing The Repeater control should only be filled with data when a team is selected We do this in three steps First, you wire up an event handler so that when the name of the...   2 Switch to Design view and drag a Calendar control into the third cell of the table, as shown in Figure 10-28 Name this calendar EventCalendar: 355 Chapter 10 Figure 10-28 3 Click the lightning bolt in the Properties pane to display the available events, . database list; see Figures 10 -13 , 10 -14 , and 10 - 15 : Figure 10 -13 If you are using Microsoft Access, ensure that a copy of the database is placed into the BegASPNET 11 WroxUnitedDatabase folder. has been used instead. 3 35 ASP. NET Server Controls Figure 10 -16 8. Click Next, and you can test out the query. You should see a screen similar to Figure 10 -17 : Figure 10 -17 9. In the final screen,. Figure 10 -10 3. Drag a DataList control into the first cell of the table from the Web Controls panel on the left, as shown in Figure 10 -11 : Figure 10 -11 4. Let's do some

Ngày đăng: 13/08/2014, 04:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan