IN THIS CHAPTER
Unless you’re creating the most basic of applications on the web, your application will need to interact with data. It will need to retrieve data from some location for display to the user or perhaps for being processed by business logic. You will also surely need to be able to send data to a data source. Sending data to a data source takes place when you need to change existing data, create new data, or delete existing data. All of these operations are standard for pretty much any web application that does anything more than simply display static text.
This chapter shows you the basics of how data binding works in ASP 2005 and how you can use the new controls, classes, and functionality to dramatically speed up the development time for data-bound Web Forms, increasing scalability, performance and ease of maintenance in the process.
Data binding refers to the act of “binding” user interface elements to underlying data through some means. This chapter does not focus much on how previous versions of ASP.NET accomplished data binding except to briefly compare and contrast. Although the new ASP.NET controls can be bound the “old way” as well as the new ASP 2005 way, you will see a huge improvement in productivity by writing your code to take advantage of some of the new features. This section introduces you to the data source pattern that exists in both ASP 2005 and Windows Forms and how to create data sources. Finally, this section will finish up with an overview of the wide variety of controls available to you for using as-is or for extending through inheritance.
Data sources are just that: sources of data. The new data source model is designed in such a way that you can create a data source for any type of underlying data, and the UI control can then bind to the data source and not directly to the data. This allows the UI control to focus simply on rendering data and not on the underlying format of the data. For example, using various data sources you can now bind a single control to an XML document, to a DataSet
, to a strongly typed collection of objects, to the results of a stored procedure execution in SQL, or to the results of an OLEDB query, and much more.
The steps required to connect your controls to a data source are extremely simple. First, you create your data source (discussed shortly), and then you drag a bindable control onto the form, select the data source from the drop-down box, and you’re well on your way to creating a rich, interactive, and data-driven web page.
Creating a data source is a simple task. After you’ve created an empty website through Visual Studio 2005, create a new Web Form. To create a data source, you drag one of the five built-in data source components onto your form. The following is a brief description of the data source components that come with ASP.NET:
SqlDataSource
—A data source used to access data contained in a SQL Server 2000 (or higher, including SQL 2005) database.AccessDataSource
—A data source used to connect to data contained in a Microsoft Access (.mdb)
file.ObjectDataSource
—An extremely powerful data source component that allows you to connect a UI control to an arbitrary object.XmlDataSource
—A data source used to connect to data contained within an XML document.SiteMapDataSource
—A data source designed to connect to the data representing a site map.After you drag the data source onto the form, the Data Source Configuration Wizard dialog will appear. This wizard will walk you through the process of configuring all the aspects of your data source. This includes specifying the query that obtains the data as well as additional queries (or stored procedures, if applicable) used for Create, Update, and Delete operations. With those operations defined, you can then use the stock ASP.NET controls to create, retrieve, update, and delete data from your data source whether the data is in an XML file, a SQL database, an Access database, or an instance of an object within your application.
To see this in action, open the Toolbox panel in Visual Studio and drag an AccessDataSource
component onto your form. This should automatically bring up the smart tag menu. From here, click the Configure Data Source option. This will bring up a screen asking you for the filename of the Access database to which the data source will attach. Browse to the location of your Northwind.mdb
file (this file is included with Visual Studio 2005 in one of the sample directories) and click Next, bringing up the screen shown in Figure 27.1.
Figure 27.1 SELECT
statement configuration for an Access data source.
Select each column specifically (instead of clicking the asterisk) and then click Next to move to the next step in the wizard. The next step allows you to click Test Query to see a preview of the data that will be appearing in the control. After you’ve tested the query, click Finish and the Data Source Configuration Wizard will finish.
Drag a GridView
control onto the form, autoformat it however you like, and set the data source to the Access data source you just created (named AccessDataSource1
by default). When you run this page in debug, you will see output that looks like Figure 27.2.
This is great, but it only allows you to view the data. The GridView
also allows you to update and delete existing rows. The great thing about data sources is that the Create, Retrieve, Update, and Delete commands are all stored in the data source, and the control need not have any knowledge of those commands. To configure your data source for insert, update, and delete operations, go back to the Configure Data Source Wizard and click “Next” to get to the screen where you choose the columns for your SELECT
statement. Click the Advanced button and you will see the dialog shown in Figure 27.3, which asks if you want to autogenerate UPDATE
, DELETE
, and INSERT
statements.
Figure 27.2 A GridView
connected to an Access data source.
Figure 27.3 Dialog prompting to autogenerate UPDATE
, DELETE
, and INSERT
statements.
Before you think this is actually going to work, go into the properties for the data source and take a look at the InsertQuery
, UpdateQuery
, and DeleteQuery
properties. There is an extremely useful miniature query builder that will pop up when you open these properties. More often than not, autogenerated queries are either not efficient enough or simply don’t work at all. However, they are a good starting point for you to go in and optimize them to work properly. After a small tweak to make it work properly, the screenshot shown in Figure 27.4 shows a functioning update query.
The only thing that a GridView
can’t do is utilize the InsertQuery
property of the data source. This section won’t get into details on how to do that because the section “Using Data-Bound Controls” later in this chapter covers utilizing the various controls that can be data-bound.
Figure 27.4 A functioning update query for an Access Data source.
Almost every single control that comes with ASP.NET 2.0 can be involved in the data-binding process in some way. However, there is a smaller list of controls that are designed specifically for working in a data-bound fashion, whether it is to display and edit the details of a single row of data or to display and edit multiple rows in a sorted, paged, or even filtered way. This list is shown in Figure 27.5.
The following is a brief overview of the controls shown in the hierarchy in Figure 27.5. The next section of this chapter will show you how to use each of these controls.
AdRotator
—A standard control for rotating advertisement information from a data-bound sourceListBox
—A standard list box control that displays multiple elements at a time, and can allow single or multiple selection of itemsCheckBoxList
—A list of checkboxes that can be rendered in several modes from a data sourceDropDownList
—A traditional “combo box”-style control whose elements and currently selected item can be pulled from a data sourceRadioButtonList
—A list of radio buttons that can be rendered in several modes from a data sourceDetailsView
—A composite control that can render a detail view showing the columns and values for a specific data row
FormView
—A composite control that renders an interactive form populated by a data sourceGridView
—A grid-style view of data from a data source that is extremely powerful and can support in-line edit and deletion of dataFigure 27.5 Hierarchy of controls that support data binding.
Many controls support binding, but thanks to the use of the data source model, many of the simpler controls are self-explanatory and easy to work with, such as the CheckBoxList
and the ListBox
. This section covers some of the more powerful controls and gives you an introduction to their use. For a more thorough examination of all ASP.NET 2.0 controls, you should consider reading one of the books that are specific to ASP.NET 2.0, such as ASP 2005 Unleashed, from Sams Publishing (ISBN: 0672328232).
GridView
ControlEarlier in this chapter you saw a brief introduction to the GridView
control. This control is responsible for rendering a list of items in a grid format, and can be configured to allow for inline editing and deleting of existing rows if the data source to which the control is connected has a DeleteCommand
and an UpdateCommand
defined. If you set the AutoGenerateDeleteButton
, AutoGenerateEditButton,
and AutoGenerateSelectButton
properties, the manual tasks previously required of the DataGrid
in ASP.NET 1.1 will be taken care of. In fact, you won’t have to write any of your own update code because the data source will perform the update (or delete) at the request of the GridView
.
DetailsView
ControlThe DetailsView
control is used for displaying the details for a single row of data. Most often when a user interface calls for the display of multiple rows of data in a grid format, the same interface requires that a row’s details eventually be displayed, either on the same page or on a different page.
If you’ve been following along, drag a DetailsView
control onto the form and set its data source to the same as the GridView
, AccessDatasource1
. Make sure to set the EnablePaging
property to true. The one thing to keep in mind that is to the DetailsView
control, one row is equivalent to one page. Therefore, to set the row being viewed or edited, you simply set the PageIndex
property.
With both a GridView
and a DetailsView
on the same page, you might assume that if you click the Select button on the GridView
(this button appears when your GridView
allows row selection), the DetailsView
will automatically move to the selected row. This would be true if the data source supported the notion of currency (maintaining current row in state), but ASP.NET 2.0 data sources do not support currency, with good reason. To make a GridView
and a DetailsView
sync up when the user selects a row in the GridView
, all you have to do is add the following line of code to the GridView
’s SelectedIndexChanged
event handler:
DetailsView1.PageIndex = GridView1.SelectedIndex;
If you’re familiar with ASP.NET 1.1 programming, you are probably wondering where the call to DataBind()
is for the DetailsView.
There is no need because all new ASP.NET 2.0 controls that support data binding indicate to the ASP.NET framework whether or not something has changed with the control that requires it to rebind. This facet of ASP.NET saves a lot of time and effort on behalf of the programmer, who no longer has to write complicated code to determine whether binding needs to take place or create convoluted workarounds to avoid double-binding the same data.
FormView
ControlThe FormView
control is similar to the DetailsView
control. The main difference between the two is that the DetailsView
is preconfigured to work in tabular data fashion, whereas the FormView
requires the developer to define the templates for items in read-only and edit mode.
To see the FormView
in action, create a new Web Form and copy the AccessDataSource1
data source from the previous page onto the new page. Then, drag a FormView
onto the page and make sure to enable paging (remember that one page on a detail/form control is the same as one row in a grid control).
Set the control up so that the form view control looks as follows:
The really important piece to remember in the preceding code is the Eval
method. This method is a part of the Page
class itself and, as such, is available through partial class technology to the code on the .aspx
page. It is far easier syntax to use than the DataBinder.Eval()
method that was required by ASP.NET 1.1 and earlier. In short, it will evaluate the property indicated on whatever data context is applicable for the template. In the case of the preceding code, it is evaluating the properties on a single row of the Customers
table in the Northwind sample Access database. You can also pass a format string to this method to further control the output.
TreeView
The TreeView
control (found in the “Navigation” section of the Toolbox) is a data-bound control that is responsible for rendering data in a hierarchical fashion. Tree-style controls are extremely useful for displaying hierarchies such as the relationship between parent rows and child rows, site navigation trees, and much more.
Although you can manually populate the nodes of a TreeView
control programmatically, this section will show you how to bind a TreeView
to a data source. This control is a hierarchical control and as such must be bound to a hierarchical data source, such as a site map or an XML data source.
One of the best features of the TreeView
control is that you can use a design-time editor to graphically pick out which attributes will supply the node labels and which attributes will supply node values given a certain hierarchy.
To see how this all works, create a new page called TreeView.aspx
and drag a TreeView
control onto the page. Now add a new XML file to the App_Data
folder in the solution and call it BuddyList.xml
. Enter the following XML for the file:
With the XML file in place, you can create an XML Data source using the BuddyList.xml
file as a source.
Open up the smart tag menu on the TreeView
control and select the XML data source as the data source. Then select the option to configure the TreeNode
data bindings. A dialog like the one shown in Figure 27.6 will appear, allowing you to select the attributes that populate various nodes of the tree. You can also autoformat the tree view for a specific application, such as a Contact list in this scenario.
When you run the page you can see how the XML file you created has been mapped onto the hierarchical structure of the TreeView
control, as shown in Figure 27.7.
Figure 27.6 TreeNode
data bindings editor.
Figure 27.7 A TreeView
autoformatted for Contacts bound to an XML file.
You can do a lot of things with data-bound controls. When you get out of the realm of small sample applications, you often start creating your own controls and creating multi-tier applications. The discussion of creating your own controls is better left to a book specializing on ASP.NET, such as ASP 2005 Unleashed, from Sams Publishing (0672328232).
When you begin adding tiers to your application, binding directly to a connected data source such as SQL Server or Oracle becomes impractical. In addition, you might be pulling data from a web service or from some other service provided by code written for the Windows Communication Framework. In these cases you don’t want to bind directly to the data source for a number of reasons, not the least of which include potentially poor performance and scalability. To deal with multiple tiers or other situations where you want to bind to custom data, you can use an ObjectDataSource
.
Object data sources are data sources that read and write information to a class instance rather than to a connected source such as SQL Server or Oracle. To create an object data source, all you have to do is drag an Object Data Source onto your form and choose the class to which it will be bound.
This means that you’ll have to create the class before you drag the object data source control. In an n-tier application scenario, this probably won’t be difficult because many n-tier applications have business objects that supply strongly typed properties as well as methods to support the standard CRUD (Create, Retrieve, Update, Delete) functionality.
This sample will show you how to create an Object Data Source from a typed DataSet
. This is the quickest way to get an object data source running from scratch because an object data source requires you to create your own implementation of the create, retrieve, update, and delete methods. After you have tried object binding with a typed DataSet
, you can move on to implementing it with your own business objects.
The first step is to add a typed DataSet
to your project. I created a typed DataSet
called UsersDataSet
, which has basic schema support for a string-based user ID, a first name, and last name. These users are stored in a SQL Express database on my machine. When you create a new DataSet
in your solution, it will prompt you to choose a connection string and will allow you to automatically connect the DataSet
to a database such as SQL Express. Although you don’t have to connect your DataSet
to a live source of data, it does make this sample easier.
With the DataSet
created, you can then drag an ObjectDataSource
component onto your Web Form. Use the wizard to select the data source. When you select the typed DataSet
, the wizard will recognize the data object immediately and automatically select the appropriate methods for Select, Create, Update, and Delete operations.
Finally, with the ObjectDataSource
created, you can drag a GridView
component onto your form and select the object data source you just created as the data source.
Figure 27.8 shows the combination of the GridView
control running against an ObjectDataSource
. When you run this page, the GridView
and the ObjectDataSource
will enable a user to edit the contents of the data set, while persisting those same contents to a connected database, all without requiring you to write a single line of code.
Figure 27.8 A GridView
and an ObjectDataSource
working against a typed DataSet
.
This chapter introduced you to the new method of binding user interface controls to various sources of data in the new version of ASP.NET. Although the old DataBind()
syntax is still available, the new method of using data sources such as a SQL data source, XML data source, or object data sources is quicker, easier, and can produce some extremely powerful results with very little effort on the part of the programmer.
If you want more detail on how data binding works, and how to create your own custom data-bound controls, you can look at ASP 2005 Unleashed by SAMS Publishing (0672328232). This chapter provides enough of an overview of data-bound controls to get you into Visual Studio and coding.
3.144.48.204