Code-Free Data Binding

One of the major goals of ASP.NET since version 1.0 has been to allow developers to achieve more while writing less code. Server controls such as the DataGrid , as well as the rest of the ASP.NET page architecture and postback mechanism, remove the need for code that iterates through rowsets, generates HTML table elements, and manages the values of controls between postbacks.

However, one area that seems to have been ignored until now is data access. In ASP.NET 1.x, you still have to create functions or routines that connect to the data store, extract the rows or values, and then expose them to the server controls in the page. OK, so that's generally not difficult, and it does provide plenty of flexibility. But it's still effort you have to put in when building the pages.

In ASP.NET 2.0, Microsoft has added new controls that take away the need for this code. Data source controls allow declarative definition of all the information required to extract the data from the data source, and they react to events within the page framework to fetch this data and display it in other data-bound controls to which they are attached.

Displaying Data with a Data Source Control

As a simple example and a dramatic indication of how easy it is to do, Listing 3.1 shows the complete declaration of the <form> section of a page that displays rows from a database. This is all you needthere is no server-side code in the page at all.

Listing 3.1 Displaying Data with a Data Source Control
 <form runat="server"> <asp:SqlDataSource id="ds1" runat="server"   ConnectionString="server=localhost;database=Northwind;uid=  x  ;pwd=  x  "   SelectCommand="SELECT ProductID, ProductName, QuantityPerUnit,                  UnitPrice, UnitsInStock, Discontinued FROM Products" /> <asp:GridView id="grid1" DataSourceID="ds1" runat="server" /> </form> 

The SqlDataSource control uses a connection string and a SQL statement (or a stored procedure name ), plus sensible default settings, to connect to a database and extract the data rows. It reacts to the page-level events that occur when the page is requested and internally builds the usual ADO.NET objects it needs (either a Connection , DataAdapter , and DataSet or a Connection , Command , and DataReader ). If you think about it, when you create these objects yourself all you start out with is the connection string and a SQL statement!

The other control, the GridView , displays the data. The GridView is a new version of the DataGrid from ASP.NET 1.0, enhanced with a lot of new features. Notice how it is connected to the data source control using the DataSourceID attribute. All ASP.NET server controls that support data binding expose this attribute in version 2.0, so they can be used interchangeably with any data source control.

The screenshot in Figure 3.1 shows the result of the code in Listing 3.1. You can see that it looks rather like the output you would get from the version 1.0 DataGrid control. It displays all the rows from the Products table in the Northwind database, just as specified in the SQL statement. Notice the Discontinued column, however. This is a Boolean field in the table, and the control automatically displays it using read-only (disabled) checkboxes.

Figure 3.1. Displaying data with a data source control

graphics/03fig01.gif

Adding Row Sorting Capabilities

Another example of the power of the GridView control can be seen when you want to allow the user to sort the rows in the grid. In ASP.NET 1.0, with the DataGrid , this was relatively easy. It meant adding a couple of attributes to the control declaration and writing a dozen or so lines of code. However, with the GridView , all you need to do is add the AllowSorting attribute to the control declaration:

 <asp:GridView id="grid1" DataSourceID="ds1" runat="server"  AllowSorting="True"  /> 

There's no code to write, no events to handle, and nothing more to do. The control looks after everything for you. Of course, you can provide custom sorting features if you want, but it's not a requirement.

Adding Row Paging Capabilities

Another common requirement, which was a little more difficult to do in version 1.0 with the DataGrid , is to add "paging" so that only a specific number of rows are shown each time and the display provides links to go to other pages. Again, with the GridView , it's just a matter of adding one attribute to the control declaration:

 <asp:GridView id="grid1" DataSourceID="ds1" runat="server"               AllowSorting="True"  AllowPaging="True"  /> 

As before, there's no code to write. It just works. The screenshot in Figure 3.2 shows the result of adding the attributes that enable sorting and paging to the basic GridView declaration.

Figure 3.2. Paging with a GridView control

graphics/03fig02.gif

You can see that only ten rows are displayed by default, and the paging controls at the bottom of the window provide links to the other pages. Also notice that the column headings are now hyperlinksthe grid now supports sorting as well. The screenshot in Figure 3.3 shows the result of clicking the ProductName heading. Repeated clicks alternate between ascending and descending sort order.

Figure 3.3. Sorting with a GridView control

graphics/03fig03.gif

Built-in Small-Screen and Mobile Device Support

The GridView control is part of the unified control architecture we discuss in more detail in Chapter 10, using an adapter to generate the appropriate device-dependent markup for clients that load the page. Tables and grids are notoriously difficult for small-screen devices to display, and Microsoft has addressed this issue by creating two different modes for displaying data in a table: summary view and details view.

The GridView control supports this approach automatically. If you open the page shown in Figure 3.2 in a suitable mobile device or device emulator, you'll see that the control renders the content using these two views. Figures 3.4 and 3.5 show the kind of output you can expect, though it does of course differ depending on the device.

Figure 3.4. Mobile device output in summary view

graphics/03fig04.gif

Figure 3.5. Mobile device output in details view

graphics/03fig05.gif

In Figure 3.4 the grid is in summary view. You can see the ProductName column heading and below it the values from that column. All of these are links. Selecting the column heading link causes the data to be sorted on the values in the column. Each product name below the column heading provides a link to display more details about that product (the other values from that row in the table).

Figure 3.5 shows the output after selecting a product in the previous screen. The grid is now in details view, and the values of the selected product are shown. Notice how the checkbox for the Discontinued column is represented in a way that suits the device. Following all the values are the links to switch back to summary view or to move to the next or previous row.

Specifying the Summary View Column

All this output is created automatically and does not require any developer effort. However, one point worth bearing in mind is that by default the summary view will display the first column. In the figures we showed the second column (the product name) as the summary column. To achieve this, just add the SummaryViewColumn attribute to the declaration of the GridView control and specify the column name:

 <asp:GridView id="grid1" DataSourceID="ds1" runat="server"      AllowSorting="True"      AllowPaging="True"  SummaryViewColumn="ProductName"  /> 

It's worth adding this attribute every time you use a GridView so that small-screen devices see the most useful column. It doesn't affect the display for "normal" devices in any way.

Linking Page Controls and Data Source Control Parameters

A regular requirement for pages that display data is to include one or more controls that can be used to select or filter the rows displayed. For example, you may display a list of countries and then show only the rows from a table of customer details for that country. The data source controls can be used to fill both the list of countries and the rows for a particular country when the user makes a selection.

The example in Listing 3.2 uses two data source controls. The first, with ID value ds1 , retrieves a list of the countries in the rows of the Customers table using the DISTINCT keyword in the SQL statement. These rows are then displayed in an ASP.NET DropDownList control by assigning the data source control to the DataSourceID property of that control and specifying the column to be displayed as the DataTextField attribute. Notice also that the DropDownList control has AutoPostback set to True , so selecting a country will cause a postback to the server.

Listing 3.2 Linking Data Source Control Parameters
 <asp:SqlDataSource id="ds1" runat="server"   ConnectionString="server=localhost;database=Northwind;uid=x;pwd=x;"   SelectCommand="SELECT DISTINCT Country FROM Customers                  ORDER BY Country"   EnableCaching="True" CacheDuration="300" /> <asp:DropDownList id="lstCountry" DataSourceID="ds1"   DataTextField="Country" AutoPostback="True" runat="server" /> ... 

One extremely useful feature of the data source controls is the ability to cache the data they retrieve, thus reducing server loading and improving performance in cases where the data is not expected to change between postbacks. The EnableCaching and CacheDuration attributes are discussed later in this chapter, along with the ability to link the cache to the original data source so that changes to the data will invalidate the cache.

Specifying and Using the Country Parameter

The next section of code in this page declares the second data source control and the GridView control (see Listing 3.3). The data source control ds2 has a SQL statement for the SelectCommand attribute that contains the parameter WHERE Country = @Country . There is also a SelectParameters section within the data source control declaration. This declares a ControlParameter named Country that takes its value from the Selected Value property of the control named lstCountry (the data-bound DropDownList populated with the country names that is declared in Listing 3.2). Finally, a GridView control is bound to the ds2 data source.

Listing 3.3 Linking Data Source Control Parameters
 ... <asp:SqlDataSource id="ds2" runat="server"   ConnectionString="server=localhost;database=Northwind;uid=x;pwd=x;"   SelectCommand="SELECT * FROM Customers WHERE Country = @Country">   <SelectParameters>     <asp:ControlParameter Name="Country" ControlID="lstCountry"                           PropertyName="SelectedValue" />   </SelectParameters> </asp:SqlDataSource> <asp:GridView id="grid1" DataSourceID="ds2" runat="server" /> 

When the page is executed, the ControlParameter is populated with the value currently selected in the DropDownList control, then this parameter is added to the data source control's Parameters collection before the SQL statement is executed. All this happens automatically, and no code is required. The data source control then selects only the rows that satisfy the parameter value and displays these in the GridView control. You can see the result in the screenshot in Figure 3.6.

Figure 3.6. Using control parameters with a data source control

graphics/03fig06.gif

Editing Data with a GridView and a Data Source Control

As a final example of the power of the new combination of data source controls and the GridView control, this section looks at in-line editing of the data within a GridView control. And, like all of the previous examples, no code is required to make it work.

In fact, there is a small section of code in this example, which we discuss when we look at how you can react to events raised by the GridView control in Chapter 4, but this is not usually required for the simple editing and deleting of rows demonstrated here.

To enable in-line editing of rows, the declaration of the data source control must include a value for the UpdateCommand attribute, and to allow rows to be deleted, the DeleteCommand attribute must be defined. In Listing 3.4, both are SQL statements including parameters that will be populated from the GridView control automatically in response to Update and Delete commands. The automatic parameter population also gives a useful extra benefit by helping to protect against SQL scripting attacks that can occur if you use values typed in by users.

The GridView control declaration also requires a few "extra" attribute values to be defined. You must specify the DataKeyNames attribute value as a comma-delimited list of primary key column names so that the control can locate the correct values for the key in the table and prevent editing of the key values. In this case it's just ShipperID . And, so that the Edit, Update, and Delete links will appear in the grid, you must set the AutoGenerate EditButton and AutoGenerateDeleteButton attributes to True .

Listing 3.4 A Data Source Control with Edit Commands
 <asp:SqlDataSource id="ds1" runat="server"   ConnectionString="server=localhost;database=Northwind;uid=x;pwd=x;"   SelectCommand="SELECT * FROM Shippers"   UpdateCommand="UPDATE Shippers SET CompanyName=@CompanyName,                  Phone=@Phone WHERE ShipperID=@ShipperID"   DeleteCommand="DELETE FROM Shippers WHERE ShipperID=@ShipperID" /> <asp:GridView id="grid1" DataSourceID="ds1" runat="server"   DataKeyNames="ShipperID"   AutoGenerateEditButton="True"   AutoGenerateDeleteButton="True" /> 

And that is all that is required to make it work. The screenshot in Figure 3.7 shows the grid with all the rows in normal mode, as it appears when first loaded. The Edit and Delete links appear in the first column.

Figure 3.7. Selecting a row to edit with a data source control

graphics/03fig07.gif

Clicking an Edit link switches that row in the grid to edit mode, and the value of the non-key columns can be edited (see Figure 3.8). Notice that the ShipperID column, the primary key specified in the DataKeyNames attribute, is not editable.

Figure 3.8. Updating a row with a data source control

graphics/03fig08.gif

After editing the values, the Update link pushes the changes back into the database using the SQL statement specified for the UpdateCommand , while the Cancel link just switches the row back to normal mode without persisting the changes to the row values. Likewise, the Delete link uses the SQL statement specified as the DeleteCommand to remove the row that contains the link.

However, because the table has linked child rows in the Products table, you can't actually delete a row with this example. Instead, the page handles the delete action and displays a message. You'll see more about this in Chapter 4 in the subsection Handling a GridView Event.

So, having seen just how powerful this new approach to data access, display, and editing is, and how easy it is to achieve, the remaining sections of this chapter and all of the next chapter look in more depth at the controls themselves and the more advanced techniques that you can take advantage of when working with them.

The DetailsView Control

All of the examples shown previously in this chapter use a GridView control to display the data rows. The GridView provides the ubiquitous "grid" layout that is so familiar with controls such as the DataGrid in version 1.x. However, often you want to display data so that only one "row" or "record" is visible, allowing users to scroll through the rowsand perhaps to edit the values as well. The second of the new data-bound controls in ASP.NET, the DetailsView control, does just that.

We'll be looking in more depth at the GridView and DetailsView controls in Chapter 4. However, just to complete this first look at the controls, the screenshot in Figure 3.9 shows the DetailsView control in action. You'll see how this works in the next chapter.

Figure 3.9. Viewing rows with a DetailsView control

graphics/03fig09.gif



A First Look at ASP. NET v. 2.0 2003
A First Look at ASP. NET v. 2.0 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net