Data Source Controls

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.

  • Data binding without requiring any code to be written . You can display, edit, and sort data with little or no code required. A data source control has the same kind of simple declarative persistence format, using HTML-like elements, as other ASP.NET server controls. Where code is required, the data source controls make it intuitive and concise .

  • A consistent declarative and programming model , regardless of the type of data source or data provider. Developers use the same syntax irrespective of the data source, and control authors have a common interface to implement in their custom data source controls.

  • A self-describing interface that makes it easy to discover the capabilities of the control. Boolean properties indicate whether SELECT , INSERT , UPDATE , DELETE , and sorting operations are supported for the data source. Code in the page can test for these capabilities, and custom control authors can implement automatic behavior when certain capabilities are available.

  • A richer design-time experience . Development tools can make it easier to generate instances of the controls and the data binding statements, perhaps using drag-and-drop design techniques. The controls can use a schema to display the data at design time in a way that more closely resembles the runtime appearance.

  • The same flexibility as in version 1.0 , by allowing developers to take full control of the data binding process and react to events (though there should be far less need to do so).

  • Performance equal to or exceeding that of version 1.0 when retrieving data and displaying it through data binding.

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.

ADO.NET 2.0 itself now supports paged results sets, so if you need to use paging with a large number of rows you may prefer to use this technique rather than a data source control. See the companion book to this one, A First Look at ADO.NET and System.Xml v. 2.0 (Boston, MA: Addison-Wesley, 2004, ISBN 0-321-22839-1) for more details.

Types of Data Source Controls

Data 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.

  • The SqlDataSource control is the one you'll use for most of your relational database access requirements. It can be used with a database through the SQL Server provider (using the classes from the SqlClient namespace), through OLE-DB, or through ODBC.

  • The AccessDataSource control makes it easy to connect to a Microsoft Access database. This is just one of the database-specific controls; other types of data sources can be accessed through specific data source controls that are under development at the time of writing.

  • The XmlDataSource control can expose hierarchical XML documents and XML data for data binding to controls such as a TreeView , as well as exposing the data as an XmlDataDocument.

  • The DataSetDataSource control exposes nonhierarchical XML as a rowset for data binding, as well as exposing the data as an ADO.NET DataSet and an XmlDataDocument.

  • The ObjectDataSource control allows developers to interact with a data access layer consisting of suitable classes, rather than directly with the database.

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 Control

For 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 Control

All 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 Attributes

Table 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

Property/Attribute

Description

ConnectionString

Sets or returns the connection string that the control uses to access the database as a String value. The format of the string must match the requirements of the database provider specified for the ProviderName . If no ProviderName is specified, the control assumes that SQL Server TDS will be used. For security reasons, the ConnectionString property is not stored in the viewstate of the page.

ProviderName

Sets or returns the namespace that contains the data provider used by the control as a String . The default is System.Data.SqlClient . The providers that are available are listed in the <providerConfiguration> section of the <system.data> element in machine.config .

DataSourceMode

Sets or returns the type of object that the control will use to access the database as a value from the SqlDataSourceMode enumeration. The available values are DataSet and DataReader . A DataReader provides better performance but does not allow for caching, filtering, or sorting within the control. The default is SqlDataSourceMode.DataSet .

SelectCommand

Sets or returns a String that specifies the SQL statement or stored procedure name that will be used to extract the data from the database. Parameters are passed to the SQL statement or stored procedure by using a <SelectParameters> element or by assigning values at runtime to the SelectParameters property (discussed later in this chapter).

InsertCommand

Sets or returns a String that specifies the SQL statement or stored procedure name that will be used to insert rows into the database. Parameters are passed to the SQL statement or stored procedure by using an <InsertParameters> element or by assigning values at runtime to the InsertParameters property (discussed later in this chapter).

UpdateCommand

Sets or returns a String that specifies the SQL statement or stored procedure name that will be used to update existing rows within the database. Parameters are passed to the SQL statement or stored procedure by using an <UpdateParameters> element or by assigning values at runtime to the UpdateParameters property (discussed later in this chapter).

DeleteCommand

Sets or returns a String that specifies the SQL statement or stored procedure name that will be used to delete rows from the database. Parameters are passed to the SQL statement or stored procedure by using a <DeleteParameters> element or by assigning values at runtime to the DeleteParameters property (discussed later in this chapter).

FilterExpression

Sets or returns a String that contains the expression to be used to filter the data specified in the SelectCommand property. It is valid only when the DataSourceMode is DataSet . The syntax of the filter expression is the same as that used in the RowFilter property of an ADO.NET DataView . Parameters should be prefixed with the @ character (or a character specific to the database). For example: "FieldName1=value1, FieldName2='value2'" "FieldName=@param"

EnableCaching

Sets or returns a Boolean value that specifies whether caching will be applied to the data selected in the control. It is valid only when the DataSourceMode is DataSet . When True , the data is cached and used in subsequent Select operations. The default is False .

CacheDuration

Sets or returns the number of seconds that data is cached when EnableCaching=True , as an Integer . The CacheExpirationPolicy property determines whether this is an absolute or sliding window value. If not specified, the data is cached for all subsequent Select operations.

CacheExpirationPolicy

Sets or returns a value from the DataSourceCache Expiry enumeration that specifies the expiry policy for the cache, as defined in the CacheDuration property. Valid values are Absolute or SlidingWindow . The default is DataSourceCacheExpiry.Absolute .

SqlCacheDependency

Sets or returns an optional cache dependency as a String . The syntax is of the form connection:table-name . The connection refers to a named entry within the <cache> section of machine.config or web.config . The tablename refers to the name of the table in the database. Multiple dependencies can be delimited with a semicolon, for example: connection:table1;connection:table2 . The database must be configured to support SQL cache invalidation .

Specifying Parameters for the SqlDataSource Control

To 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:

  • The value of a server control within the page, using a ControlParameter control

  • A name/value pair that appears in the Request.QueryString collection, using a QueryStringParameter control

  • A value from a control that appears in the Request.Form collection, using a FormParameter control

  • A value stored in the user 's ASP.NET session, using a SessionParameter control

  • A value in a cookie sent by the browser with the request, using a CookieParameter control

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

Property

Description

SelectParameters

Returns a reference to the ParameterCollection containing the parameters for the Select operation.

UpdateParameters

Returns a reference to the ParameterCollection containing the parameters for the Update operation.

InsertParameters

Returns a reference to the ParameterCollection containing the parameters for the Insert operation.

DeleteParameters

Returns a reference to the ParameterCollection containing the parameters for the Delete operation.

FilterParameters

Returns a reference to the ParameterCollection containing the parameters used to filter the rows returned by a Select operation.

Parameter Properties and Attributes

The 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

Property/Attribute

Description

Name

Sets or returns the name of the parameter as a String , corresponding to the parameter in the SQL statement or stored procedure to which it will be applied. Note that the @ prefix should not be included in the name.

Direction

Sets or returns the "direction" for the parameter, as a value from the System.Data.Parameter Direction enumeration. Valid values are:

  • Input : The parameter carries an input value for the query.

  • Output : The parameter collects an output value from the query.

  • InputOutput : The parameter carries an input value for the query and returns with the value updated by the query.

  • ReturnValue : The parameter carries the value specified by a RETURN statement in a stored procedure.

DefaultValue

Sets or returns the default value of the parameter as a String representation of that value.

Type

Sets or returns the data type that the value and the DefaultValue represent, using a standard .NET TypeCode value such as String , Int16 , or Decimal .

TreatEmptyStringAsNull

Sets or returns a Boolean value that indicates whether an empty String for the value will be treated as null when the SQL statement or stored procedure is executed.

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

Parameter Control

Properties

ControlParameter

ControlID : The id of the control containing the value to use.

PropertyName : The name of the control property that contains the value, for example, Text for the Text property of a Textbox control.

QueryStringParameter

QueryStringField : The name of the name/value pair that contains the value to use, for example, UserID , where the query string contains UserID=smithron .

FormParameter

FormField : The name of the control on the page that contains the value to use. It does not have to be a server control. Corresponds to the name attribute of the control within the HTML source of the page.

SessionParameter

SessionField : The name of the key used to store the value in the user's ASP.NET session, for example, UserID , where the value was stored using Session("UserID") = "smithron" .

CookieParameter

CookieName : The name of the key used to store the value in the cookie.

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 Parameters

The 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 Runtime

The 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 Methods

The 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 Events

The 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

Method

Description

Select()

Returns all the rows specified by the SelectCommand and the values in the SelectParameters collection from the data source or from the cached DataSourceView that contains the rows. Returns a System.Data.DataView instance if the DataSourceMode property is set to DataSet , or a DataReader if the DataSourceMode property is set to DataReader . The DataReader must be explicitly closed after use.

Delete()

Deletes the row(s) specified by the DeleteCommand and the values in the DeleteParameters collection from the data source. Returns an Integer that is the number of rows deleted from the data source.

Insert()

Inserts a new row into the data source using the InsertCommand and the values in the InsertParameters collection. Returns an Integer that is the number of rows inserted into the data source table.

Update()

Updates rows in the data source using the UpdateCommand and the values in the UpdateParameters collection. Returns an Integer that is the number of rows updated in the data source.

Table 3.6. The SqlDataSource Control Events

Event

Description

Selecting

Raised before the Select method is executed. A SqlDataSourceCommandEventArgs instance passed to the event handler exposes a single property:

  • Command : A reference to the provider-specific Command instance that will be used to execute the operation.

The current operation can be canceled by returning False from the event handler.

Selected

Raised after the Select method completes. A SqlDataSourceStatusEventArgs instance passed to the event handler exposes three properties:

  • OutputParameters : Returns an ordered dictionary of the parameters from the command (usually a stored procedure) where the parameter has a Direction property value of Output or InputOutput .

  • ReturnValue : Returns the value of the parameter from the command (usually a stored procedure) where the parameter has a Direction property value of ReturnValue .

  • RowsAffected : Returns the number of data rows affected by this operation.

Deleting

Raised before the Delete method is executed. A SqlDataSourceCommandEventArgs instance is passed to the event handler (see the Selecting event for details).

Deleted

Raised after the Delete method completes. A SqlDataSourceStatusEventArgs instance is passed to the event handler (see the Selected event for details).

Inserting

Raised before the Insert method is executed. A SqlDataSourceCommandEventArgs instance is passed to the event handler (see the Selecting event for details).

Inserted

Raised after the Insert method completes. A SqlDataSourceStatusEventArgs instance is passed to the event handler (see the Selected event for details).

Updating

Raised before the Update method is executed. A SqlDataSourceCommandEventArgs instance is passed to the event handler (see the Selecting event for details).

Updated

Raised after the Update method completes. A SqlDataSourceStatusEventArgs instance is passed to the event handler (see the Selected event for details).

DataSourceChanged

Raised when the contents of the SqlDataSourceView for this control change, and causes any data-bound controls to rebind.

SqlDataSource Constructors

You 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

Constructor

Description

SqlDataSource()

Creates a new SqlDataSource instance with the default values for all the properties.

SqlDataSource (connect-string, select-command)

Creates a new SqlDataSource instance with the specified values for the ConnectionString and SelectCommand properties. All other properties are set to the default value. As the Provider property defaults to SqlClient , this only allows access to SQL Server via TDS unless you set this property to another provider namespace.

The Parameter and ParameterCollection Interfaces

A 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

Constructors

Description

Parameter()

Creates a new Parameter instance with the default values for all the properties.

Parameter( name, value-name )

Creates a new Parameter instance with the specified value for the Name property (as a String ) and the specified value-name (as a String ) for the type-specific property that identifies the source of the value (i.e., ControlID , FormField , CookieName , and so on).

Parameter( name, type-code, value-name )

Creates a new Parameter instance with the specified value for the Name property (as a String ), the specified data type (as a value from the TypeCode enumeration), and the specified value-name (as a String ) for the type-specific property that identifies the source of the value.

Method

ToString()

Returns the value of the Parameter as a String . If the value is specified as representing a different data type, the String representation of the value is returned.

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

Constructor

Description

ParameterCollection()

Creates a new empty ParameterCollection.

Properties

Count

Returns the number of parameters in the collection as an Integer.

Item(name)

Returns a reference to a parameter within the collection specified by its name as a String.

Item(index)

Returns a reference to a parameter within the collection specified by its index as an Integer.

Methods

Add(param)

Adds the specified Parameter instance to the collection. Returns the index of the parameter within the collection as an Integer.

Add(name, value)

Adds a Parameter with the specified (String) name and specified (String) value to the collection. Returns the index of the parameter within the collection as an Integer.

Add(name, type, value)

Adds a Parameter with the specified (String) name, the specified (TypeCode) data type, and the specified (String) value to the collection. Returns the index of the parameter within the collection as an Integer.

GetValues(section)

Returns an ordered dictionary containing the name/value pairs for the parameters for a specified section of the SqlDataSource control, for example, the SelectParameters or UpdateParameters section.

Insert(index, param)

Inserts the specified Parameter instance into the collection at the specified zero-based Integer index. No return value.

Remove(param)

Removes the specified Parameter instance from the collection. No return value.

RemoveAt(index)

Removes the parameter at the specified zero-based Integer index position within the collection. No return value.

UpdateValues(section)

Updates the parameters for a specified section of the SqlDataSource control with the values returned by executing the operation for that section. No return value.

Event

ParametersChanged

Raised when the value of a parameter in the collection changes (e.g., following a Select method call), when a value is changed in code, or when a parameter is added to or removed from the collection.

The SqlDataSourceView Interface

Every 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

Constructor

Description

SqlDataSourceView(owner, name)

Raised when the value of a parameter in the collection changes (e.g., following a Select method call), when a value is changed in code, or when a parameter is added to or removed from the collection.

SqlDataSourceView Properties

The 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

Property

Description

Name

Returns the name of this SqlDataSourceView instance as a String .

CanDelete

Returns a Boolean value that indicates whether rows can be deleted from this SqlDataSourceView instance. Returns False if the DeleteCommand property is empty.

CanInsert

Returns a Boolean value that indicates whether rows can be inserted into this SqlDataSourceView instance. Returns False if the InsertCommand property is empty.

CanUpdate

Returns a Boolean value that indicates whether rows can be updated within this SqlDataSourceView instance. Returns False if the UpdateCommand property is empty.

CanSort

Returns a Boolean value that indicates whether the rows in this SqlDataSourceView instance can be sorted. Returns False if the DataSourceMode property of the owning SqlDataSource control property is not set to DataSet .

SortExpression

Sets or returns a String that defines the sort order for the rows in this SqlDataSourceView instance. This is a comma-delimited list of column names , each optionally suffixed with DESC for a descending sort. This property applies only when the DataSourceMode property of the owning SqlDataSource control is set to DataSet .

SqlDataSourceView Methods

The 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 Event

The 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

Method

Description

Delete(parameters)

Deletes row(s) using the parameters specified as a dictionary of name/value pairs. Returns the number of rows deleted as an Integer .

Insert(values)

Inserts a new row using the values specified as a dictionary of name/value pairs. Returns the number of rows inserted as an Integer .

Update(parameters, values)

Updates row(s) using the parameters specified as a dictionary of name/value pairs, and the values specified as a dictionary of name/value pairs. Returns the number of rows updated as an Integer .

Table 3.13. The SqlDataSourceView Event

Event

Description

DataSourceViewChanged

Raised when the contents of the SqlDataSourceView change, which raises the DataSourceChanged event for the owner DataSourceControl and causes any data-bound controls to rebind.

The AccessDataSource Control

The 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

Property

Description

DataFile

Sets or returns the relative path to the .mdb database file as a String and is used in place of the ConnectionString property. The value is passed to the Server.MapPath method to convert it to a full physical path before appending it to the ConnectionString .

ShareMode

Sets or returns a value from the System.IO.FileAccess enumeration that specifies the way the database file is accessed. Valid values are Read , ReadWrite , and Write . The default is Read . The account you specify for access to the file, or the anonymous process account under which ASP.NET is running if you don't specify a UserID and Password , must have the appropriate permission to access the file in the specified mode.

UserID

Sets or returns the user ID under which the database file is accessed as a String . Optional; added to the ConnectionString if a value is provided.

Password

Sets or returns the password that will be used to access the database file as a String . Optional; added to the ConnectionString if a value is provided.

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 Control

The 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:

  • The XmlDataSource control, which is designed to expose hierarchical XML and is ideal for binding to controls such as a TreeView , which can display nested data

  • The DataSetDataSource control, which works only with nonhierarchical ("flat") data structures such as a single data table

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 Control

Since 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 Interface

The 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

Property

Description

DataFile

Sets or returns the relative or absolute path to the XML data file to use as input. This property accepts a String value.

ReadOnly

Sets or returns a Boolean value that indicates whether the XML document will be opened in read-only mode. The default is True . When set to False , the XML document is opened in read-write mode and the CanInsert , CanUpdate , and CanDelete properties of the DataSetDataSourceView will return True .

SchemaFile

Sets or returns the relative or absolute path to a schema that defines the structure of the XML. This property accepts a String value.

TransformFile

Sets or returns the relative or absolute path to an XSL or XSLT document that will be used to transform the XML data before it is exposed by the control. This property accepts a String value.

AutoSave

Sets or returns a Boolean value that indicates whether changes to the data will be saved back to the XML disk file automatically, as soon as a change is made. The default is True . When set to False , the Save method must be called to update the XML disk file. This can be used to reduce disk accesses.

XPath

Sets or returns a String containing an XPath statement that filters or selects elements from the source document. Has the same kind of effect as applying a FilterExpression with the SqlDataSource control.

UniqueID

Returns a String value that acts as a unique identifier for the document.

Data

Sets or returns the XML content that will be used as the source data, as a String . This property can be set declaratively using the Data child element within the main XmlDataSource element. The DataFile property must be empty in this case.

Schema

Sets or returns the schema content that defines the data structure, as a String . This property can be set declaratively using the Schema child element within the main XmlDataSource element. The SchemaFile property must be empty in this case.

Transform

Sets or returns the XSL or XSLT document that will be used to transform the data before it is exposed by the control, as a String . This property can be set declaratively using the Transform child element within the main XmlDataSource element. The TransformFile property must be empty in this case.

TransformArgumentList

Gives a reference to an XsltArgumentList instance containing the arguments that will be used in the transformation process when using the TransformFile or Transform properties to specify an XSLT stylesheet. This property should be set in the On Transforming event to ensure that the arguments are available when the transformation is applied.

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

Method

Description

GetXmlDataDocument()

Returns a reference to an XmlDataDocument instance that contains the XML representation of the source data from the control.

Save()

Persists the current values in the control to the XML disk file.

Table 3.17. The XmlDataSource Control Events

Event

Description

OnTransforming

Raised before the control applies any XSL or XSLT stylesheet to the XML source data. Useful if you need to provide an XsltArgumentList reference to thecontrol before the data is bound to other controls in the page.

OnDataSourceChanged

Raised when the data source for the control changes, allowing data-bound controls to rebind to the data source control.

The DataSetDataSource Control

The 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 Control

The 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 Interface

As 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

Method

Description

GetDataSet()

Returns a reference to the DataSet that is the source of the data from the control.

The ObjectDataSource Control

All 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 Control

The 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 Interface

The 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

Property

Description

ClassName

A String that contains the type name of the object to create. This can be a partially qualified name such as MyClass or a fully qualified name such as MyNamespace.MyClass .

SelectMethod

The method of the object to invoke for a SELECT operation. Any parameters required can be defined as the SelectParameters property or in the nested SelectParameters element of the control declaration.

UpdateMethod

The method of the object to invoke for an UPDATE operation. Any parameters required can be defined as the UpdateParameters property or in the nested UpdateParameters element of the control declaration.

InsertMethod

The method of the object to invoke for an INSERT operation. Any parameters required can be defined as the InsertParameters property or in the nested InsertParameters element of the control declaration.

DeleteMethod

The method of the object to invoke for a DELETE operation. Any parameters required can be defined as the DeleteParameters property or in the nested DeleteParameters element of the control declaration.

Table 3.20. The ObjectDataSource Control Events

Event

Description

ObjectCreatez

Raised immediately after the object specified by ClassName has been created. Can be used to set properties on the object instance or to call methods to prepare it for use if required.

ObjectDisposing

Raised just before the object specified by ClassName is disposed. Can be used to clean up before the object is destroyed or to call other methods on the object if required.

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 Controls

More data source controls are planned for future releases of ASP.NET, and the following may well find their way into the final release version:

  • A WebServiceDataSource control to allow you to work with data exposed by Web Services

  • An ExcelDataSource control to allow access to Excel worksheet files

  • An OracleDataSource control to allow manipulation of data in an Oracle database without using OLE-DB or ODBC directly

  • An IndexServiceDataSource control that will allow the Indexing Service catalog to be queried

  • A SharePointDataSource control that will allow interaction with the database of resources maintained in Microsoft SharePoint



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