In essence, a data source control simply replaces the data access code you create in ASP.NET 1.x to generate the rowset of data that you want to use in your page. Instead of writing a function that returns (for example) a DataSet loaded with the data rows you want to display, you just place a data source control on the page and set the properties to define the data you want. When a control such as a GridView or a DropDownList renders the data, it uses the data source control to fetch the data and expose it for data binding. Therefore, when adding a control that supports data binding to the page, you don't have to write any code at all. And the new GridView and DetailsView controls can automatically provide features to update the data as wellagain without requiring you to write any code. Meanwhile, you can still write code to interact with the controls if you want to, and you can perform customized data binding or manipulate the data directly. However, in the vast majority of cases the controls will do all the work for you. The aims of the data source controls (combined with the new GridView and DetailsView controls and data binding) are to provide the following.
To connect a data source control to a server control that will display the data, you use the DataSourceID attribute of the data-bound server controlsetting it to the id attribute value of the data source control. All the controls in the System.Web.UI.WebControls and System.Web.UI.Html Controls namespaces that already support server-side data binding now accept the DataSourceID attribute. One important point to note is that the data source controls in the Technology Preview release are not designed to support ADO.NET data row paging. Paging is available in the GridView control (as in the DataGrid control in version 1.x) but is implemented within the GridView control and not by the underlying data source control. In future releases the relational data source controls such as SqlDataSource will take advantage of ADO.NET paging features to improve performance.
Types of Data Source ControlsData source controls fall into different classes, depending on the type of data source they will be used to access. All data source controls live in the System.Web.UI.WebControls namespace of the .NET Framework class library, and all implement one or both of the IDataSource and IHierarchicalDataSource interfaces. The data source controls are listed below.
In forthcoming releases of ASP.NET you can expect to see more new data source controls such as the WebServiceDataSource , ExcelDataSource , and IndexServiceDataSource . A list of the proposed data source controls appears near the end of this chapter. Here, we'll look at each of the data source controls in the Technology Preview version individually. We'll start with the SqlDataSource control and then see how the other data source controls differ from it. The SqlDataSource ControlFor most relational database access tasks , the SqlDataSource control is the obvious choice. By default it will use a SQL Serverspecific connection, but by simply changing the connection string you can use any of the databases for which a provider is available, without having to rewrite your code or change the page in any other way. Declaring a SqlDataSource ControlAll data source controls can be instantiated through declarative elements in the page, and their properties set using attributes, just as you declare any other ASP.NET server control. The complete set of attributes you can use in a SqlDataSource control declaration is shown in Listing 3.5. Listing 3.5 Declaring a SqlDataSource Control<asp:SqlDataSource id=" String " runat="server" ConnectionString=" String " ProviderName=" String " DataSourceMode="[DataSetDataReader]" SelectCommand=" String " InsertCommand=" String " UpdateCommand=" String " DeleteCommand=" String " FilterExpression=" String " EnableCaching="[TrueFalse]" CacheDuration=" Integer " SqlCacheDependency=" String " CacheExpirationPolicy="[AbsoluteSlidingWindow]" OnSelecting=" SqlDataSourceCommandEventHandler " OnSelected=" SqlDataSourceStatusEventHandler " OnUpdating=" SqlDataSourceCommandEventHandler " OnUpdated=" SqlDataSourceStatusEventHandler " OnInserting=" SqlDataSourceCommandEventHandler " OnInserted=" SqlDataSourceStatusEventHandler " OnDeleting=" SqlDataSourceCommandEventHandler " OnDeleted=" SqlDataSourceStatusEventHandler " OnDataSourceChanged=" EventHandler " > <SelectParameters> [<System.Web.UI.WebControls.Parameter ...>] </SelectParameters> <UpdateParameters> [<System.Web.UI.WebControls.Parameter ...>] </UpdateParameters> <InsertParameters> [<System.Web.UI.WebControls.Parameter ...>] </InsertParameters> <DeleteParameters> [<System.Web.UI.WebControls.Parameter ...>] </DeleteParameters> <FilterParameters> [<System.Web.UI.WebControls.Parameter ...>] </FilterParameters> </asp:SqlDataSource> The attributes in the opening element tag correspond in a one-to-one fashion to the properties of the control listed in the next subsection, which details the complete control interface. The content of the <asp:SqlData Source> element is a series of parameter declarations that define how the control should select and filter the data and how it will update the data when changes are pushed back into the database. We'll look at these parameter declarations later in this chapter. Like all server controls, the SqlDataSource exposes an interface that you can access programmatically. When the control is inserted into the page, ASP.NET instantiates the control and uses the attributes you specify to set the properties without requiring any code to be written in the page. Of course, you can read and set the properties in code as required. SqlDataSource Properties and AttributesTable 3.1 lists the properties and attributes shown in the declaration of the control in Listing 3.5. In general, you must set at least the Connection String and SelectCommand . If you are not accessing SQL Server, you must also set the ProviderName to the namespace of the classes in the .NET Framework library that correspond to the type of data source and data access method you are using. Table 3.1. The SqlDataSource Class Properties and Attributes
Specifying Parameters for the SqlDataSource ControlTo be able to use a control to access (and update) data, there has to be a way to pass parameter values to the SQL statements or stored procedures it uses under the hood. Otherwise the value of the SelectCommand would need to be changed each time the control is required to extract a different set of rows (or to perform different updates to the database tables). So that you don't have to write code to set these parameter values, the SqlDataSource control exposes the parameters in a way that allows them to be set declaratively by referencing dynamic values that are part of the page request or the control tree. For a stored procedure, parameters are defined as part of the procedure definition within the database itself. For a SQL statement, parameters are specified using placeholders, for example: "SELECT * FROM Customers WHERE Country='@Country'" At runtime, the control replaces the @Country placeholder with the specific value of the parameter. The values that are passed to the SQL statement or stored procedure can be taken directly from:
These controls are declared within the SqlDataSource control element as a set of optional nested elements. As well as the parameters for the Select , Update , Insert , and Delete operations, there is an optional element that can be used to filter the rows returned by a Select operation (see Listing 3.6). Listing 3.6 Parameter Outline for a SqlDataSource Control<asp:SqlDataSource id=" String " runat="server" ... > <SelectParameters> ... one or more xxx Parameter elements here ... </SelectParameters> <UpdateParameters> ... one or more xxx Parameter elements here ... </UpdateParameters> <InsertParameters> ... one or more xxx Parameter elements here ... </InsertParameters> <DeleteParameters> ... one or more xxx Parameter elements here ... </DeleteParameters> <FilterParameters> ... one or more xxx Parameter elements here ... </FilterParameters> </asp:SqlDataSource> At runtime, ASP.NET creates a separate ParameterCollection for each of the sections that appear within the declaration of the control and populates these collections using the Parameter elements in each section. The ParameterCollection instances are then applied to the properties of the SqlDataSource control. These properties are shown in Table 3.2. Table 3.2. The ParameterCollection Class Properties
Parameter Properties and AttributesThe five types of parameter that you can use within the parameter sections of the SqlDataSource control are descended from the common base class System.Web.UI.WebControls.Parameter . This class exposes five properties that are inherited by all of the parameter types (see Table 3.3). Table 3.3. The Parameter Class Properties and Attributes
The five specific parameter classes expose at least one additional String property, depending on the parameter type (see Table 3.4). These properties are used to specify how the value for the parameter is selected from all the values available in the set of controls on the page, in the QueryString or Form collection, in the session, or in the cookies sent from the client. Table 3.4. The Five Parameter Section Types
Listing 3.7 shows an example of the ways that the parameter controls can be used. Each of the properties of the SqlDataSource can be set with any of the five different parameter types or with a mixture of different types. Listing 3.7 Parameter Details for a SqlDataSource Control <asp:SqlDataSource id=" String " runat="server" ... > <SelectParameters> <asp:ControlParameter Name="UserID" ControlID="txtUserID" PropertyName="Text" /> <asp:ControlParameter Name="UserName" ControlID="lstName" PropertyName="SelectedValue" /> </SelectParameters> <UpdateParameters> <asp:FormParameter Name="Country" FormField="CountryBox" /> </UpdateParameters> <InsertParameters> <asp:QueryStringParameter Name="UID" QueryStringField ="uid" /> <asp:SessionParameter Name="Page" SessionField ="PageName" /> </InsertParameters> <DeleteParameters> <asp:ControlParameter Name="UserID" ControlID="txtUserID" PropertyName="Text" /> <asp:FormParameter Name="Country" FormField="CountryBox" /> <asp:CookieParameter Name="CheckVal" CoookieName="CheckSum" /> </DeleteParameters> </asp:SqlDataSource> Remember that you need to set only the SqlDataSource properties that correspond to the operations you'll be carrying out. In other words, if you are just displaying dataand not updating ityou can omit the UpdateParameters , InsertParameters , and DeleteParameters sections. Applying a Dynamic Filter Expression with ParametersThe same approach is taken if you want to specify a filter that will be applied to the results of the SelectCommand . For example, the code in Listing 3.8 specifies the Text value of a Textbox control that has the ID txtFilterExpr . This value is used as a filter against the column named table-column-name within the results setin effect setting the FilterExpression to table-column-name=value-of-textbox . Listing 3.8 Using FilterParameters with a SqlDataSource Control ... <FilterParameters> <asp:ControlParameter Name=" table-column-name " ControlID="txtFilterExpr" PropertyName="Text" /> </FilterParameters> ... Working with the SqlDataSource Control at RuntimeThe combination of the SqlDataSource control and data-bound controls (such as the new GridView and DetailsView controls) is designed to remove the need for you to write runtime code to create output in the page. However, there are still occasions where you may want to interact with a data source control directly, for example, to modify the output based on the content of the data rows by reacting to an event that the control (or some other control on the page) raises. The next subsections list the remaining members of the interface for the SqlDataControl . SqlDataSource Control MethodsThe SqlDataSource control exposes four methods that you can call to perform data access operations through the control. Each method uses the appropriate command specified in the SelectCommand , DeleteCommand , InsertCommand , or UpdateCommand property of the control and takes into account any parameters defined for the SelectParameters , DeleteParameters , InsertParameters , or UpdateParameters properties, respectively. The four methods are shown in Table 3.5. SqlDataSource Control EventsThe SqlDataSource control raises various events as it operates on the data source or when its methods are called. The event handlers that will respond to these events can be specified within the declaration of the SqlDataSource control or added to the control at runtime by using the AddHandler method in Visual Basic .NET or by appending them to the event property in C# in the usual way. The events are shown in Table 3.6. Table 3.5. The SqlDataSource Control Methods
Table 3.6. The SqlDataSource Control Events
SqlDataSource ConstructorsYou can create an instance of a SqlDataSource control and add it to the Controls collection of the page by using one of the constructors. You also need to set the property values and then call any methods you need (such as Select or Update ). The constructors are shown in Table 3.7. Table 3.7. The SqlDataSource Constructors
The Parameter and ParameterCollection InterfacesA Parameter for use with the SqlDataSource control can be created by using one of the three constructors. It has a single method (see Table 3.8). Table 3.8. The Parameter Class Interface
The ParameterCollection class holds a collection of Parameter instances, as assigned to one of the xxx Parameters properties of the SqlDataSource control (e.g., the SelectParameters or FilterParameters property)see Table 3.9. Table 3.9. The ParameterCollection Class Interface
The SqlDataSourceView InterfaceEvery data source control exposes the data it selects from its corresponding data store as a DataSourceView . The SqlDataSource control exposes a SqlDataSourceView instance. The data-bound controls in the page then consume the SqlDataSourceView and display the data rows it contains. Of course, if you are simply declaring the SqlDataSource and GridView controls on your page and not interacting with them in code, you don't need to worry about the SqlDataSourceView itself. However, it is useful when you want to access rows and individual values in, say, an event handler. The SqlDataSourceView has a single constructor (see Table 3.10) and exposes broadly the same set of properties, methods, and events as the SqlDataSource control itself. Table 3.10. The SqlDataSourceView Constructor
SqlDataSourceView PropertiesThe SqlDataSourceView exposes the same SelectCommand , SelectParameters , UpdateCommand , UpdateParameters , InsertCommand , InsertParameters , DeleteCommand , DeleteParameters , FilterExpression , and FilterParameters properties as the SqlData Source control. Additionally there are properties that provide information about the SqlDataSourceView 's capabilities, set the sorting order, and expose the name of the SqlDataSourceView instance (see Table 3.11). Table 3.11. The SqlDataSourceView Properties
SqlDataSourceView MethodsThe SqlDataSourceView exposes the same Delete , Insert , Select , and Update methods as the SqlDataSource control, plus three methods that operate directly on rows within this SqlDataSourceView instance (see Table 3.12). SqlDataSourceView EventThe SqlDataSourceView exposes the same Selected , Selecting , Updated , Updating , Deleted , Deleting , Inserted , and Inserting events as the SqlDataSource control, plus one other event (see Table 3.13). Table 3.12. The SqlDataSourceView Methods
Table 3.13. The SqlDataSourceView Event
The AccessDataSource ControlThe AccessDataSource control inherits from SqlDataSource and carries a few extra interface members that make it easier to work with Access database files. The abridged declaration of the control shown in Listing 3.9 highlights the extra properties of this control. Listing 3.9 Declaring an AccessDataSource Control<asp:AccessDataSource runat="server" DataSourceMode= " SqlDataSourceMode " DataFile=" String " ShareMode=" FileAccess " UserID=" String " Password=" String " SelectCommand=" String " InsertCommand=" String " UpdateCommand=" String " DeleteCommand=" String " ... </asp:AccessDataSource> Table 3.14. The AccessDataSource Control Properties
The four attributes highlighted in Listing 3.9 correspond to the four properties used to construct the connection string that the AccessDataSource will use to access the database file (see Table 3.14). The XmlDataSource ControlThe data source controls we've looked at so far connect to a relational database and extract data as a series of rows and columns . However, it's becoming increasingly common to encounter data that is persisted or exposed as XML. There are two data source controls in the Technology Preview release of ASP.NET 2.0 that are designed to work with XML data:
We look at the XmlDataSource control in this subsection and the DataSetDataSource control in the following subsection. The XmlDataSource control loads an XML document and exposes the data it contains. If the XML has nested elements, giving a hierarchical structure, the control exposes the data in this way. The result is that data cannot then be bound to controls that accept only flat data structures such as a table or arrayfor example, the ordinary "list" controls. However, controls such as the TreeView expect to receive hierarchical data, and for these the XmlDataSource control is the obvious choice. Declaring an XmlDataSource ControlSince it inherits from the base DataSource class, the XmlDataSource class inherits all of the same interface members as SqlDataSource . This means that attributes you use with the SqlDataSource control (such as Enable Caching and CacheDuration ) apply equally to the XmlDataSource control. However, the control accesses an XML document (a disk file or a resource that dynamically creates and returns XML), so there are different attributes that specify how to load the XML document, plus a series of nested elements that allow the source data to be declared in-line (see Listing 3.10). Listing 3.10 Declaring an XmlDataSource Control<asp:XmlDataSource id=" String " runat="server" DataFile=" String " ReadOnly="[TrueFalse]" SchemaFile=" String " TransformFile=" String " AutoSave="[TrueFalse]" XPath=" String " UniqueID=" String " EnableCaching="[TrueFalse]" CacheDuration=" Integer " CacheExpirationPolicy="[AbsoluteSlidingWindow]" OnDataSourceChanged=" EventHandler " OnTransforming=" EventHandler " > <Data> [...Inline XML Data...] </Data> <Schema> [...Inline XML Schema...] </Schema> <Transform> [...Inline XSL/XSLT Transform...] </Transform> </asp:XmlDataSource> The attributes highlighted in Listing 3.10 are those that have not been discussed previously in this chapter. The others behave exactly as described earlier in this chapter for the SqlDataSource control. The XmlDataSource Control InterfaceThe attributes and nested elements shown highlighted in Listing 3.10 correspond to the properties in Table 3.15. Table 3.15. The XmlDataSource Control Properties
The XmlDataSource control exposes two methods you can use to interact with the control at runtime (see Table 3.16). Finally, there are two events you can handle to interact with the process (see Table 3.17 on the next page). Table 3.16. The XmlDataSource Control Methods
Table 3.17. The XmlDataSource Control Events
The DataSetDataSource ControlThe second data source control designed to handle XML data is the DataSetDataSource control. It is very similar in both declaration and interface to the XmlDataSource . Two properties are omitted, and there is one extra method. One interesting possibility for manipulating XML data is to store it in and expose it through a DataSet . And, more than that, the nature of the DataSet allows it to move between a relational and an XML-based view of that data. In effect, the DataSetDataSource control provides an interface to an instance of a DataSet and implements the same processes as other data source controls such as the SqlDataSource to support automated server-side data bindingas well as features that allow the XML source data to be updated. The DataSetDataSource also allows runtime code to access the data directly as a DataSet or as an XmlDataDocument instance, giving almost ultimate flexibility in working with the data. Declaring a DataSetDataSource ControlThe declaration of a DataSetDataSource control is almost identical to the XmlDataSource control, but without the XPath and UniqueID attributes. Again, optional nested elements can be used to declare the data, schema, and XSL/XSLT stylesheet in-line if required (see Listing 3.11). Listing 3.11 Declaring a DataSetDataSource Control<asp:DataSetDataSource id=" String " runat="server" DataFile=" String " ReadOnly="[TrueFalse]" SchemaFile=" String " TransformFile=" String " AutoSave="[TrueFalse]" EnableCaching="[TrueFalse]" CacheDuration=" Integer " CacheExpirationPolicy="[AbsoluteSlidingWindow]" OnDataSourceChanged=" EventHandler " OnTransforming=" EventHandler " > <Data> [...Inline XML Data...] </Data> <Schema> [...Inline XML Schema...] </Schema> <Transform> [...Inline XSL/XSLT Transform...] </Transform> </asp:DataSetDataSource> The DataSetDataSource Control InterfaceAs mentioned, the DataSetDataSource does not have the UniqueID and XPath properties, but otherwise the list of properties is identical to the XmlDataSource control shown earlier in this chapter. There is one extra method available on the DataSetDataSource that is not implemented by the XmlDataSource control. It can be used to directly access and manipulate the DataSet that is holding the source data (see Table 3.18). Table 3.18. The DataSetDataSource Control Method
The ObjectDataSource ControlAll of the data sources covered so far encourage a "two- tier architecture" approach to building applications. They directly access the data store (the data layer), be it a relational database or an XML document. However, the ObjectDataSource control allows developers to work with three-tier or n -tier architectures by exposing data access layer and/or custom business objects in a way suited to declarative server-side data binding. Like the other data source controls, simply declaring the ObjectDataSource control on the page and linking it to a suitable data-bound control can provide "no-code" data bindingand even editing capabilities. The only limitations are that the objects the ObjectDataSource control will access must be stateless, must expose a default constructor, and must have methods that can be directly and individually mapped to the Select , Update , Insert , and Delete actions of the control (although a subset of these can be supported if not all types of update actions are required, e.g., an application may be designed to support inserting of objects but not updates to them). Data access to objects revolves around methods that the objects expose, so ordinary SQL statements cannot be used to select or update them. Instead, the objects themselves take care of extracting values from their own data store, exposing the values, and persisting changes where appropriate. This means that a data source control that accesses objects has to provide an interface that can be used to define the processes required to extract and update data. It does this by referencing the methods within the objects that perform these processes. Declaring an ObjectDataSource ControlThe ObjectDataSource control exposes many of the same properties as the SqlDataSource control we examined earlier in this chapter. The main difference is that the operations on the data must be specified as methods of the objects referenced by the control. The differences in the declaration of the control compared to a SqlDataSource control are highlighted in Listing 3.12. Listing 3.12 Declaring an ObjectDataSource Control<asp:ObjectDataSource id=" String " runat="server" ClassName=" String " SelectMethod=" String " UpdateMethod=" String " InsertMethod=" String " DeleteMethod=" String " FilterExpression=" String " EnableCaching="[TrueFalse]" CacheDuration=" Integer " CacheExpirationPolicy="[AbsoluteSlidingWindow]" SqlCacheDependency=" String " OnSelecting=" ObjectDataSourceMethodEventHandler " OnSelected=" ObjectDataSourceMethodExecutedEventHandler " OnUpdating=" ObjectDataSourceMethodEventHandler " OnUpdated=" ObjectDataSourceMethodExecutedEventHandler " OnInserting=" ObjectDataSourceMethodEventHandler " OnInserted=" ObjectDataSourceMethodExecutedEventHandler " OnDeleting=" ObjectDataSourceMethodEventHandler " OnDeleted=" ObjectDataSourceMethodExecutedEventHandler " OnObjectCreated=" ObjectDataSourceObjectEventHandler " OnObjectDisposing=" ObjectDataSourceObjectEventHandler " > <SelectParameters> [<System.Web.UI.WebControls.Parameter ...>] </SelectParameters> <UpdateParameters> [<System.Web.UI.WebControls.Parameter ...>] </UpdateParameters> <DeleteParameters> [<System.Web.UI.WebControls.Parameter ...>] </DeleteParameters> <InsertParameters> [<System.Web.UI.WebControls.Parameter ...>] </InsertParameters> <FilterParameters> [<System.Web.UI.WebControls.Parameter ...>] </FilterParameters> </asp:ObjectDataSource> The ObjectDataSource Control InterfaceThe highlighted sections of Listing 3.12 of the ObjectDataSource control show the attributes, and hence the properties, that are different from the SqlDataSource control. These are listed in Table 3.19. Table 3.19. The ObjectDataSource Control Properties
Table 3.20. The ObjectDataSource Control Events
The ObjectDataSource exposes the same events as the SqlDataSource , though these accept different types of "argument" classes. The events that occur before an operation on the data (i.e., Selecting , Inserting ) pass an instance of the ObjectDataSourceMethodEventArgs class to the event handler. The events that occur after an operation on the data (i.e., Selected , Inserted ) pass an instance of the ObjectDataSourceMethodExecuted EventHandler class to the event handler. Both of these argument classes expose a reference to the method that was called as a MethodInfo instance. There are also two extra events for the ObjectDataSource , which are invoked after an instance of the class that the data source will use is created and before it is disposed, respectively. Both events pass an ObjectDataSourceEventArgs instance as an argument to the event handler, which exposes the ObjectInstance property containing a reference to the object instance just created or disposed (see Table 3.20). Possible Forthcoming Data Source ControlsMore data source controls are planned for future releases of ASP.NET, and the following may well find their way into the final release version:
|