Now that you can control access to your application, you can turn your attention to querying and maintaining data. You will useWeb Server Data controls to connect to the database, query data, and maintain the data, in a manner similar to that used by the Windows Forms application you built in Chapter 24, “Working with Data Binding and DataSets.”
In the following exercises, you will fetch all of the rows in the Customers table in the Microsoft SQL Server Northwind Traders database and display them in a GridView. The first task is to create a connection that you can use to connect to the Northwind database.
Display the CustomerData.aspx page in the Design View window. Delete the label displaying “This form will be implemented later.”
In the Toolbox, expand the Data category. Add a SqlDataSource control to the Web form.
Click anywhere in the form to hide the SqlDataSource Tasks menu that appears. A control called SqlDataSource1 is added to the Web form. The SqlDataSource control is a Web Server control that performs the same tasks as a data source in a Windows Forms application.
Using the Properties window, change the (ID) property of SqlDataSource1 to CustomerInfoSource.
Select the CustomerInfoSource control on the Web Form. Click the Smart Tag icon to display the SqlDataSource Tasks menu, and then click the Configure Data Source link.
The Configure Data Source Wizard appears. This is very similar (but not identical) to the wizard you saw in Chapter 23. You will use it to create a connection to the database and fetch the data from the Customers table.
Click the New Connection button. Use the Add Connection page to create a new connection with the values shown in the following table. Click OK when you have finished.
Microsoft SQL Server (SqlClient)
Log on to the server
Use windows authentication
Select or enter a database name
In the Configure Data Source Wizard, click Next.
In the Save the Connection String to the Application Configuration file screen, save the connection string as NorthwindConnectionString and click Next.
In the Configure the Select Statement page, ensure “Specify columns from a table or view” is selected. Select the Customers table in the Name drop-down list box. In the Columns list box, check “*”.
Click Advanced. In the Advanced SQL Generation Options dialog box, check “Generate INSERT, UPDATE, and DELETE statements.” Click OK, and then click Next.
In the Test Query page, click Test Query.
The data from the Customers table appears in the grid in the dialog box.
Click the Smart Tag icon to hide the SqlDataSource Tasks menu.
In the next exercise, you will add a GridView control to the CustomerData Web form and bind it to the CustomerInfoSource data source.
In the Toolbox, click the GridView control. Drag it onto the form. Click anywhere on the form to hide the GridView Tasks menu that appears.
A GridView is added to the form and displays placeholder data. Resize the GridView so that it fills most of the form.
Using the Properties window, change the (ID) property of the GridView control to CustomerGrid.
With the GridView control still selected, click the Smart Tag icon to display the GridView Tasks menu. In the GridView Tasks menu, click the Auto Format link.
In the Auto Format dialog box, select the Classic scheme and then click OK.
In the GridView Tasks menu that is still displayed, select CustomerInfoSource from the Choose Data Source drop-down list.
The column headings for the Customers table appear in the GridView control on the screen.
Click the Smart Tag icon to hide the GridView Tasks menu.
On the Debug menu, click Start Without Debugging.
Internet Explorer starts and displays the Log In page.
Log in as John with password Pa$$w9rd.
The CustomerData page appears displaying the details of every customer in the database:
Notice that the page is currently read-only; you cannot modify any of the details displayed. You will enhance the Web form later in this chapter to enable the user to make changes.
Close Internet Explorer when you have finished browsing the data and return to Visual Studio 2005.
Fetching the details of every customer is very useful, but suppose there are a large number of rows in the Customers table. It is highly unlikely that a user would actively want to browse thousands of rows, so generating a long page displaying them all would be a waste of time and network bandwidth. Instead, it would be far better to display data in chunks and allow the user to page through that data. This is what you will do in the following set of exercises.
Ensure that CustomerData.aspx is displayed in the Design View window. Select the CustomerGrid control. In the Properties window, set the AllowPaging property to True.
A footer is added to the GridView containing a pair of page numbers. This footer is referred to as the pager. You can format the pager in many different ways. The style shown is the default format, comprising page numbers that the user can click.
In the Properties window, set the PageSize property to 8.
This will cause the GridView to display data in eight-row chunks.
Expand the PagerStyle composite property. You can use this property to specify how the pager should be formatted. Set HorizontalAlign sub-property to Left.
The numbers in the pager move to the left marginin the GridView control.
Expand the PagerSettings composite property. Use the values in this property to specify how page navigation links are formatted. You can specify page navigation links in two ways: as page numbers, or as next/previous page arrows. Set the Mode property to NumericFirstLast to display page numbers with the first and last page arrows displayed to enable the user to move quickly to the start or end of the data. Set the PageButtonCount sub-property to 5; this will cause page links to be displayed in groups of five (you will see what this does when you run the Web application).
If you want to use next/previous page arrows, you can change the default text displayed (“>” and “<”) by modifying the values of the NextPageText and PreviousPageText properties. Similarly, you can change the text displayed for the first and last page links by editing the FirstPageText and LastPageText properties. Notice that the values in these properties require encoding as HTML characters; otherwise, they will not be displayed properly (for example, the “>” symbol is specified as “>”). If you prefer, you can also specify the name of an image file in the FirstPageImageUrl, LastPageImageUrl, PreviousPageImageUrl and NextPageImageUrl properties. The page navigation links will appear as buttons containing these images if supported by the browser.
Run the Web application.
After logging in, the first eight rows of data and a set of page links are displayed on the CustomerData Web form. Page numbers 1, 2, 3, 4, and 5 are displayed, together with “>>” to move directly to the last page. Clicking the “…” link displays the next five page numbers together with a “<<” link for moving directly back to the first page. An additional “…” link provides access to the previous five pages.
Click the links at the bottom of the grid to move from page to page.
Close Internet Explorer and return to the Visual Studio 2005 programming environment when you have finished browsing the data.
In this chapter, you have been using a SqlDataSource control to connect to the database and fetch the data. Behind the scenes, the SqlDataSource control creates a DataSet. When you bind a Web Server Data control such as GridView to a data source, Visual Studio 2005 generates code that populates the DataSet and displays it in the data control.
DataSets are very powerful objects. You have seen in earlier chapters how they can act as in-memory datastore and how you can use them to update a database. However, this power comes at a price. A DataSet that contains a large number of rows will itself be very large and can consume considerable resources. If you are using a GridView to simply display data rather than modify it, using a DataSet may be too cumbersome a solution. The SqlDataSource control has a property called DataSourceMode which you can set to DataSet (the default) or DataReader. Specifying a value of DataReader causes the data source to open an ADO.NET DataReader object for retrieving data. A DataReader implements a very efficient mechanism for fetching data as a read-only stream. For more information, see the sidebar “Firehose Cursors” in Chapter 23. However, one drawback of using a DataReader is that it does not support paging.
A DataSet contains a copy of the data it fetches. The longer the DataSet is held, the more out-of-date the information it holds can become. How can you make certain that the data a user sees in a Web form is the current data without continually refilling the DataSet? If you examine the SqlDataSource control, you will find that it has three properties that you can use to help solve this problem:
Whenever you display a Web form that contains a SqlDataSource control, the SQL SELECT statement specified by that control is executed to populate its DataSet. By default, if you use paging to display, and the rows displayed are spread over several pages, the SQL SELECT statement will be executed whenever you move from one page to another. The SQL SELECT statement will also be executed again if you simply refresh the view of the Web form in the browser. In this way, you are always presented with a copy of the data that is up-to-date when the Web form is displayed.
However, if none of the data actually changes between displaying or refreshing pages, you are wasting database resources by repeatedly connecting to and querying the database. If you set the EnableCaching property to True, the DataSet will act as a cache and the SQL SELECT statement will only be re-executed based on the settings of two other properties: CacheDuration, and CacheExpirationPolicy.
This property specifies how frequently the SQL SELECT statement is re-executed and the cache refreshed. Its default setting of Infinite means that the cache never expires and so will never be refreshed. Setting it to a numeric value specifies the expiration period of the cache, in seconds.
This property is used in conjunction with CacheDuration to determine how frequently the cache is updated. If this property is set to its default value of Absolute, then the cache will always be refreshed every CacheDuration seconds. If this property is set to Sliding, then the cache will only be refreshed after CacheDuration seconds of inactivity in the application.
In the next exercise, you will see the effects of modifying the cache settings of a SqlDataSource control.
Ensure that CustomerData.aspx is displayed in the Design View window. Select the CustomerInfoSource control. In the Properties window, set the EnableCaching property to True. Verify that the CacheDuration property is set to Infinite, and the CacheExpiration Policy property is set to Absolute.
This combination of settings causes the DataSet generated by the SqlDataSource control to act as a cache that never expires. The cache will be populated when the Web form is first displayed, but will never be refreshed when moving from page to page or refreshing the Web form.
Run the Web application. Log in and display the first page of Customer data.
Notice that the value in the City column of the first row (ALFKI) is Berlin.
Leave the Web application running, and open a Command Prompt window. In the Command Prompt window, type the following command:
sqlcmd –S YourServer\SQLExpress –E
Replace YourServer with the name of your computer. This command starts the SQL Server command line tool, allowing you to connect to a database and run SQL statements.
A 1> prompt is displayed by the sqlcmd tool.
At the 1> prompt, type the following statements (the prompt will change each time you press the Enter key):
USE Northwind GO UPDATE Customers SET City = 'Bonn' WHERE CustomerID = 'ALFKI' GO
The message (1 row affected) is displayed. This command changes the value of the City column for the first customer from Berlin to Bonn.
Leave the Command Prompt window open and return to the Web application running in Internet Explorer. Move to page 2, and then return to page 1. Notice that the City for the first row has not changed—it is still Berlin. Close the Web application and return to Visual Studio 2005.
Select the CustomerInfoSource control again. In the Properties window, set the Cache Duration property to 10 (ensure EnableCaching is still set to True).
The DataSet generated by the SqlDataSource control now expires after 10 seconds, and will be updated. You will see the changes if you redisplay the page after the expiration period.
Run the Web application again. Log in and display the first page of Customer data. Notice that the value in the City column of the first row (ALFKI) is now Bonn (this is the change you made earlier).
Return to the sqlcmd tool running in the Command Prompt window. At the 1> prompt, type the following statements:
UPDATE Customers SET City = 'Munich' WHERE CustomerID = 'ALFKI' GO
The message (1 row affected) is displayed again. This command changes the value of the City column for the first customer from Bonn to Munich.
Wait for more than 10 seconds and then return to the Web application running in Internet Explorer. Move to page 2, and then return to page 1. Notice that the City for the first row has changed to Munich as the DataSet has been refreshed. Close the Web application.
Close the Command Prompt window.