.NET Framework Class Library ObjectDataSource Class Represents a business object that provides data to data-bound controls in multitier Web application architectures.

Inheritance Hierarchy
Namespace:
System.Web.UI.WebControls
Assembly:
System.Web (in System.Web.dll)

Syntax
<ToolboxBitmapAttribute(GetType(ObjectDataSource))> _
Public Class ObjectDataSource _
Inherits DataSourceControl
[ToolboxBitmapAttribute(typeof(ObjectDataSource))]
public class ObjectDataSource : DataSourceControl
[ToolboxBitmapAttribute(typeof(ObjectDataSource))]
public ref class ObjectDataSource : public DataSourceControl
[<ToolboxBitmapAttribute(typeof(ObjectDataSource))>]
type ObjectDataSource =
class
inherit DataSourceControl
end
The ObjectDataSource type exposes the following members.

Constructors

Properties
|
| Name | Description |
|---|
.gif) | Adapter | Gets the browser-specific adapter for the control. (Inherited from Control.) | .gif) | AppRelativeTemplateSourceDirectory | Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control. (Inherited from Control.) | .gif) | BindingContainer | Infrastructure. Gets the control that contains this control's data binding. (Inherited from Control.) | .gif) | CacheDuration | Gets or sets the length of time, in seconds, that the data source control caches data that is retrieved by the SelectMethod property. | .gif) | CacheExpirationPolicy | Gets or sets the cache expiration behavior that, when combined with the duration, describes the behavior of the cache that the data source control uses. | .gif) | CacheKeyDependency | Gets or sets a user-defined key dependency that is linked to all data cache objects that are created by the data source control. | .gif) | ChildControlsCreated | Gets a value that indicates whether the server control's child controls have been created. (Inherited from Control.) | .gif) | ClientID | Gets the server control identifier generated by ASP.NET. (Inherited from DataSourceControl.) | .gif) | ClientIDMode | This property is not used for data source controls. (Inherited from DataSourceControl.) | .gif) | ClientIDSeparator | Gets a character value representing the separator character used in the ClientID property. (Inherited from Control.) | .gif) | ConflictDetection | Gets or sets a value that determines whether or not just the new values are passed to the Update method or both the old and new values are passed to the Update method. | .gif) | Context | Gets the HttpContext object associated with the server control for the current Web request. (Inherited from Control.) | .gif) | Controls | Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. (Inherited from DataSourceControl.) | .gif) | ConvertNullToDBNull | Gets or sets a value indicating whether the Parameter values that are passed to an update, insert, or delete operation are automatically converted from nullNothingnullptra null reference (Nothing in Visual Basic) to the Value value by the ObjectDataSource control. | .gif) | DataItemContainer | Gets a reference to the naming container if the naming container implements IDataItemContainer. (Inherited from Control.) | .gif) | DataKeysContainer | Gets a reference to the naming container if the naming container implements IDataKeysControl. (Inherited from Control.) | .gif) | DataObjectTypeName | Gets or sets the name of a class that the ObjectDataSource control uses for a parameter in an update, insert, or delete data operation, instead of passing individual values from the data-bound control. | .gif) | DeleteMethod | Gets or sets the name of the method or function that the ObjectDataSource control invokes to delete data. | .gif) | DeleteParameters | Gets the parameters collection that contains the parameters that are used by the DeleteMethod method. | .gif) | DesignMode | Gets a value indicating whether a control is being used on a design surface. (Inherited from Control.) | .gif) | EnableCaching | Gets or sets a value indicating whether the ObjectDataSource control has data caching enabled. | .gif) | EnablePaging | Gets or sets a value that indicates whether the data source control supports paging through the set of data that it retrieves. | .gif) | EnableTheming | Gets a value indicating whether this control supports themes. (Inherited from DataSourceControl.) | .gif) | EnableViewState | Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client. (Inherited from Control.) | .gif) | Events | Gets a list of event handler delegates for the control. This property is read-only. (Inherited from Control.) | .gif) | FilterExpression | Gets or sets a filtering expression that is applied when the method that is specified by the SelectMethod property is called. | .gif) | FilterParameters | Gets a collection of parameters that are associated with any parameter placeholders in the FilterExpression string. | .gif) | HasChildViewState | Gets a value indicating whether the current server control's child controls have any saved view-state settings. (Inherited from Control.) | .gif) | ID | Gets or sets the programmatic identifier assigned to the server control. (Inherited from Control.) | .gif) | IdSeparator | Infrastructure. Gets the character used to separate control identifiers. (Inherited from Control.) | .gif) | InsertMethod | Gets or sets the name of the method or function that the ObjectDataSource control invokes to insert data. | .gif) | InsertParameters | Gets the parameters collection that contains the parameters that are used by the InsertMethod property. | .gif) | IsChildControlStateCleared | Gets a value indicating whether controls contained within this control have control state. (Inherited from Control.) | .gif) | IsTrackingViewState | Gets a value that indicates whether the server control is saving changes to its view state. (Inherited from Control.) | .gif) | IsViewStateEnabled | Gets a value indicating whether view state is enabled for this control. (Inherited from Control.) | .gif) | LoadViewStateByID | Gets a value indicating whether the control participates in loading its view state by ID instead of index. (Inherited from Control.) | .gif) | MaximumRowsParameterName | Gets or sets the name of the business object data retrieval method parameter that is used to indicate the number of records to retrieve for data source paging support. | .gif) | NamingContainer | Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same Control..::.ID property value. (Inherited from Control.) | .gif) | OldValuesParameterFormatString | Gets or sets a format string to apply to the names of the parameters for original values that are passed to the Delete or Update methods. | .gif) | Page | Gets a reference to the Page instance that contains the server control. (Inherited from Control.) | .gif) | Parent | Gets a reference to the server control's parent control in the page control hierarchy. (Inherited from Control.) | .gif) | RenderingCompatibility | Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with. (Inherited from Control.) | .gif) | SelectCountMethod | Gets or sets the name of the method or function that the ObjectDataSource control invokes to retrieve a row count. | .gif) | SelectMethod | Gets or sets the name of the method or function that the ObjectDataSource control invokes to retrieve data. | .gif) | SelectParameters | Gets a collection of parameters that are used by the method specified by the SelectMethod property. | .gif) | Site | Gets information about the container that hosts the current control when rendered on a design surface. (Inherited from Control.) | .gif) | SkinID | Gets the skin to apply to the DataSourceControl control. (Inherited from DataSourceControl.) | .gif) | SortParameterName | Gets or sets the name of the business object that the SelectMethod parameter used to specify a sort expression for data source sorting support. | .gif) | SqlCacheDependency | Gets or sets a semicolon-delimited string that indicates which databases and tables to use for the Microsoft SQL Server cache dependency. | .gif) | StartRowIndexParameterName | Gets or sets the name of the data retrieval method parameter that is used to indicate the value of the identifier of the first record to retrieve for data source paging support. | .gif) | TemplateControl | Gets or sets a reference to the template that contains this control. (Inherited from Control.) | .gif) | TemplateSourceDirectory | Gets the virtual directory of the Page or UserControl that contains the current server control. (Inherited from Control.) | .gif) | TypeName | Gets or sets the name of the class that the ObjectDataSource object represents. | .gif) | UniqueID | Gets the unique, hierarchically qualified identifier for the server control. (Inherited from Control.) | .gif) | UpdateMethod | Gets or sets the name of the method or function that the ObjectDataSource control invokes to update data. | .gif) | UpdateParameters | Gets the parameters collection that contains the parameters that are used by the method that is specified by the UpdateMethod property. | .gif) | ViewState | Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page. (Inherited from Control.) | .gif) | ViewStateIgnoresCase | Gets a value that indicates whether the StateBag object is case-insensitive. (Inherited from Control.) | .gif) | ViewStateMode | Gets or sets the view-state mode of this control. (Inherited from Control.) | .gif) | Visible | Gets or sets a value indicating whether the control is visually displayed. (Inherited from DataSourceControl.) | Top

Methods
|
| Name | Description |
|---|
.gif) | AddedControl | Called after a child control is added to the Controls collection of the Control object. (Inherited from Control.) | .gif) | AddParsedSubObject | Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object. (Inherited from Control.) | .gif) | ApplyStyleSheetSkin | Applies the style properties that are defined in the page style sheet to the control. (Inherited from DataSourceControl.) | .gif) | BuildProfileTree | Infrastructure. Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page. (Inherited from Control.) | .gif) | ClearCachedClientID | Infrastructure. Sets the cached ClientID value to nullNothingnullptra null reference (Nothing in Visual Basic). (Inherited from Control.) | .gif) | ClearChildControlState | Deletes the control-state information for the server control's child controls. (Inherited from Control.) | .gif) | ClearChildState | Deletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearChildViewState | Deletes the view-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.) | .gif) | CreateChildControls | Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. (Inherited from Control.) | .gif) | CreateControlCollection | Creates a collection to store child controls. (Inherited from DataSourceControl.) | .gif) | DataBind()()() | Binds a data source to the invoked server control and all its child controls. (Inherited from Control.) | .gif) | DataBind(Boolean) | Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event. (Inherited from Control.) | .gif) | DataBindChildren | Binds a data source to the server control's child controls. (Inherited from Control.) | .gif) | Delete | Performs a delete operation by calling the method that is identified by the DeleteMethod property with any parameters that are in the DeleteParameters collection. | .gif) | Dispose | Enables a server control to perform final clean up before it is released from memory. (Inherited from Control.) | .gif) | EnsureChildControls | Determines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.) | .gif) | EnsureID | Creates an identifier for controls that do not have an identifier assigned. (Inherited from Control.) | .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) | FindControl(String) | Searches the current naming container for a server control with the specified id parameter. (Inherited from DataSourceControl.) | .gif) | FindControl(String, Int32) | Infrastructure. Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method. (Inherited from Control.) | .gif) | Focus | Sets input focus to the control. (Inherited from DataSourceControl.) | .gif) | GetDesignModeState | Infrastructure. Gets design-time data for a control. (Inherited from Control.) | .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetRouteUrl(Object) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(String, Object) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | GetUniqueIDRelativeTo | Returns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.) | .gif) | GetView | Retrieves the named data source view that is associated with the data source control. (Overrides DataSourceControl..::.GetView(String).) | .gif) | GetViewNames | Retrieves a collection of names representing the list of view objects that are associated with the ObjectDataSource object. (Overrides DataSourceControl..::.GetViewNames()()().) | .gif) | HasControls | Determines if the server control contains any child controls. (Inherited from DataSourceControl.) | .gif) | HasEvents | Returns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.) | .gif) | Insert | Performs an insert operation by calling the method that is identified by the InsertMethod property and any parameters in the InsertParameters collection. | .gif) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Restores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.) | .gif) | LoadViewState | Infrastructure. Loads the previously saved view state of the ObjectDataSource control. (Overrides Control..::.LoadViewState(Object).) | .gif) | MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.) | .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | OnBubbleEvent | Determines whether the event for the server control is passed up the page's UI server control hierarchy. (Inherited from Control.) | .gif) | OnDataBinding | Raises the DataBinding event. (Inherited from Control.) | .gif) | OnInit | Adds a LoadComplete event handler to the page that contains the ObjectDataSource control. (Overrides Control..::.OnInit(EventArgs).) | .gif) | OnLoad | Raises the Load event. (Inherited from Control.) | .gif) | OnPreRender | Raises the PreRender event. (Inherited from Control.) | .gif) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RaiseDataSourceChangedEvent | Raises the DataSourceChanged event. (Inherited from DataSourceControl.) | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | Render | Sends server control content to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.) | .gif) | RenderChildren | Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.) | .gif) | RenderControl(HtmlTextWriter) | Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. (Inherited from DataSourceControl.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.) | .gif) | ResolveAdapter | Gets the control adapter responsible for rendering the specified control. (Inherited from Control.) | .gif) | ResolveClientUrl | Gets a URL that can be used by the browser. (Inherited from Control.) | .gif) | ResolveUrl | Converts a URL into one that is usable on the requesting client. (Inherited from Control.) | .gif) | SaveControlState | Saves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.) | .gif) | SaveViewState | Infrastructure. Saves the state of the ObjectDataSource control. (Overrides Control..::.SaveViewState()()().) | .gif) | Select | Retrieves data from the underlying data storage by calling the method that is identified by the SelectMethod property with the parameters in the SelectParameters collection. | .gif) | SetDesignModeState | Sets design-time data for a control. (Inherited from Control.) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.) | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Infrastructure. Tracks view-state changes to the ObjectDataSource control so that they can be stored in the System.Web.UI..::.StateBag object. (Overrides Control..::.TrackViewState()()().) | .gif) | Update | Performs an update operation by calling the method that is identified by the UpdateMethod property and any parameters that are in the UpdateParameters collection. | Top

Events

Extension Methods

Explicit Interface Implementations
|
| Name | Description |
|---|
.gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | For a description of this member, see IControlBuilderAccessor..::.ControlBuilder. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.GetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.SetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. For a description of this member, see IControlDesignerAccessor..::.SetOwnerControl. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | For a description of this member, see IControlDesignerAccessor..::.UserData. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | For a description of this member, see IDataBindingsAccessor..::.DataBindings. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | For a description of this member, see IDataBindingsAccessor..::.HasDataBindings. (Inherited from Control.) | .gif) .gif) | IDataSource..::.DataSourceChanged | Infrastructure. Occurs when a data source control has changed in a way that affects data-bound controls. (Inherited from DataSourceControl.) | .gif) .gif) | IDataSource..::.GetView | Infrastructure. Gets the named DataSourceView object associated with the DataSourceControl control. Some data source controls support only one view, while others support more than one. (Inherited from DataSourceControl.) | .gif) .gif) | IDataSource..::.GetViewNames | Infrastructure. Gets a collection of names, representing the list of DataSourceView objects associated with the DataSourceControl control. (Inherited from DataSourceControl.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | For a description of this member, see IExpressionsAccessor..::.Expressions. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | For a description of this member, see IExpressionsAccessor..::.HasExpressions. (Inherited from Control.) | .gif) .gif) | IListSource..::.ContainsListCollection | Infrastructure. Indicates whether the data source control is associated with one or more lists of data. (Inherited from DataSourceControl.) | .gif) .gif) | IListSource..::.GetList | Infrastructure. Gets a list of data source controls that can be used as sources of lists of data. (Inherited from DataSourceControl.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | Top

Remarks
In this topic: IntroductionThe ObjectDataSource is an ASP.NET data source control that represents a data-aware middle-tier object or a data interface object to data-bound controls. You can use the ObjectDataSource control in conjunction with a data-bound control to display, edit, and sort data on a Web page with little or no code. There is no visual rendering of the ObjectDataSource control. It is implemented as a control so that you can create it declaratively and to enable it to participate in state management, optionally. As a result, the ObjectDataSource does not support visual features such as the EnableTheming or SkinID property. PurposeA very common application design practice is to separate the presentation layer from business logic and to encapsulate the business logic in business objects. These business objects form a distinct layer between the presentation layer and the data tier, resulting in a three-tier application architecture. The ObjectDataSource control enables developers to use an ASP.NET data source control while retaining their three-tier application architecture. The ObjectDataSource control uses reflection to create instances of business objects and to call methods on them to retrieve, update, insert, and delete data. The TypeName property identifies the name of the class that the ObjectDataSource works with. The ObjectDataSource control creates and destroys an instance of the class for each method call; it does not hold the object in memory for the lifetime of the Web request. This is a serious consideration if the business object that you use requires many resources or is otherwise expensive to create and destroy. Using an expensive object might not be an optimal design choice, but you can control the life cycle of the object by using the ObjectCreating, ObjectCreated, and ObjectDisposing events. Retrieving DataTo retrieve data from a business object, set the SelectMethod property with the name of the method that retrieves data. If the method does not return an IEnumerable or DataSet object, the object is wrapped by the runtime in an IEnumerable collection. If the method signature has parameters, you can add Parameter objects to the SelectParameters collection, and then bind them to the values that you want to pass to the method that is specified by the SelectMethod property. In order for the ObjectDataSource to use the parameters, the parameters must match the names and types of the parameters in the method signature. For more information, see Using Parameters with the ObjectDataSource Control. The ObjectDataSource control retrieves data whenever the Select method is called. This method provides programmatic access to the method that is specified by SelectMethod property. The method that is specified by the SelectMethod property is called automatically by controls that are bound to the ObjectDataSource when their DataBind method is called. If you set the DataSourceID property of a data-bound control, the control automatically binds to data from the data source, as needed. Setting the DataSourceID property is the recommended method for binding an ObjectDataSource control to a data-bound control. Alternatively, you can set the DataSource property, but then you must explicitly call the DataBind method of the data-bound control. You can call the Select method programmatically at any time to retrieve data. For more information about binding data-bound controls to data source controls, see Binding to Data Using a Data Source Control. Performing Data OperationsDepending on the capabilities of the business object that the ObjectDataSource control works with, you can perform data operations, such as updates, insertions, and deletions. To perform these data operations, set the appropriate method name and any associated parameters for the operation that you want to perform. For example, for an update operation, set the UpdateMethod property to the name of the business object method that performs updates and add any required parameters to the UpdateParameters collection. If the ObjectDataSource control is associated with a data-bound control, the parameters are added by the data-bound control. In this case, you need to ensure that the parameters names of the method match the field names in the data-bound control. The update is performed when the Update method is called, either explicitly by your code or automatically by a data-bound control. The same general pattern is followed for Delete and Insert operations. Business objects are assumed to perform these types of data operations one record at a time, rather than batched. Filtering DataThe ObjectDataSource control can filter data that is retrieved by the SelectMethod property, if the data is returned as a DataSet or DataTable object. The ObjectDataSource control allows you to cache all types of data, but you should not cache objects that retain resources or state that cannot be shared to service multiple requests (for example, an open SqlDataReader object), because the same instance of the object will be used to service multiple requests. You can set the FilterExpression property to a filtering expression by using a format string syntax and bind values in the expression to parameters that are specified in the FilterParameters collection. CachingAlthough the ObjectDataSource does not retain the instance of the business object across multiple requests, it can cache the result of the SelectMethod property. While the data is cached, subsequent calls to the Select method return the cached data instead of creating the business object and calling its SelectMethod using reflection. Caching lets you avoid creating the object and calling its data method at the expense of memory on the Web server. The ObjectDataSource automatically caches data when the EnableCaching property is set to true, and the CacheDuration property is set to the number of seconds that the cache stores data before the cache is discarded. You can also specify a CacheExpirationPolicy property and an optional SqlCacheDependency property. FeaturesThe following table describes the features of the ObjectDataSource control. Capability | Requirements |
|---|
Selecting | Set the SelectMethod property to the name of the business object method that selects data, and include any necessary parameters in the SelectParameters collection either programmatically or by using a data-bound control. | Sorting | Set the SortParameterName property to the name of the parameter in the SelectMethod method that carries the sort criteria. | Filtering | Set the FilterExpression property to a filtering expression and optionally add any parameters to the FilterParameters collection to filter the data when the Select method is called. The method specified by the SelectMethod property must return a DataSet or DataTable. | Paging | Data source paging is supported, if the SelectMethod method contains parameters for the maximum number of records to retrieve and the index of the first record to retrieve. The names of those parameters must be set in the MaximumRowsParameterName and StartRowIndexParameterName properties, respectively. A data-bound control might be able to perform paging itself, even if the ObjectDataSource control does not support paging directly in the method specified by the SelectMethod property. The requirement for the data-bound control to be able to do this is that the method specified by the SelectMethod property return an object that implements the ICollection interface. | Updating | Set the UpdateMethod property to the name of the business object method that updates data, and include any necessary parameters in the UpdateParameters collection. | Deleting | Set the DeleteMethod property to the name of the business object method or function that deletes data, and include any necessary parameters in the DeleteParameters collection. | Inserting | Set the InsertMethod property to the name of the business object method or function that inserts data, and include any necessary parameters in the InsertParameters collection. | Caching | Set the EnableCaching property to true, and the CacheDuration and CacheExpirationPolicy properties according to the caching behavior you want for your cached data. |
Note |
|---|
When you use the ObjectDataSource class to update or insert data, strings that are entered at the client are not automatically converted from the client culture format to the server culture format. For example, the client culture might specify DD/MM/YYYY as the date format, and the date format on the server might be MM/DD/YYYY. In that case, October 5, 2009 would be entered in a TextBox control as 5/10/2009 but would be interpreted as May 10, 2009. October 15, 2009 would be entered as 15/10/2009, and would be rejected as an invalid date. |
Data ViewAs with all data source controls, the ObjectDataSource control is associated with a data source view class. While the ObjectDataSource control is the interface that the page developer uses to work with data, the ObjectDataSourceView class is the interface that data-bound controls work with. Additionally, the ObjectDataSourceView class describes the capabilities of the data source control, and performs the actual work. The ObjectDataSource control has only one associated ObjectDataSourceView, and it is always named DefaultView. While the ObjectDataSourceView object is exposed by the GetView method, many of its properties and methods are wrapped and exposed directly by the ObjectDataSource control. Behind the scenes, the ObjectDataSourceView object performs all data operations, including retrieving, inserting, updating, deleting, filtering, and sorting the data. For more information, see ObjectDataSourceView. Using LINQ to SQLYou can use the ObjectDataSource control with a LINQ to SQL class. To do so, you set the TypeName property to the name of the data-context class. You also set the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod methods to the methods in the data-context class that perform the corresponding operations. You must create an event handler for the ObjectDisposing event in order to cancel disposing of the data-context class. This step is necessary because LINQ to SQL supports deferred execution, whereas the ObjectDataSource control tries to dispose the data context after the Select operation. For more information about how to create LINQ to SQL classes, see How to: Create LINQ to SQL Classes in a Web Application. For an example of how to cancel the disposing of a data context class, see the ObjectDisposing event. Declarative Syntax
<asp:ObjectDataSource
CacheDuration="string|Infinite"
CacheExpirationPolicy="Absolute|Sliding"
CacheKeyDependency="string"
ConflictDetection="OverwriteChanges|CompareAllValues"
ConvertNullToDBNull="True|False"
DataObjectTypeName="string"
DeleteMethod="string"
EnableCaching="True|False"
EnablePaging="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
FilterExpression="string"
ID="string"
InsertMethod="string"
MaximumRowsParameterName="string"
OldValuesParameterFormatString="string"
OnDataBinding="DataBinding event handler"
OnDeleted="Deleted event handler"
OnDeleting="Deleting event handler"
OnDisposed="Disposed event handler"
OnFiltering="Filtering event handler"
OnInit="Init event handler"
OnInserted="Inserted event handler"
OnInserting="Inserting event handler"
OnLoad="Load event handler"
OnObjectCreated="ObjectCreated event handler"
OnObjectCreating="ObjectCreating event handler"
OnObjectDisposing="ObjectDisposing event handler"
OnPreRender="PreRender event handler"
OnSelected="Selected event handler"
OnSelecting="Selecting event handler"
OnUnload="Unload event handler"
OnUpdated="Updated event handler"
OnUpdating="Updating event handler"
runat="server"
SelectCountMethod="string"
SelectMethod="string"
SkinID="string"
SortParameterName="string"
SqlCacheDependency="string"
StartRowIndexParameterName="string"
TypeName="string"
UpdateMethod="string"
Visible="True|False"
>
<DeleteParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</DeleteParameters>
<FilterParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</FilterParameters>
<InsertParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</InsertParameters>
<SelectParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</UpdateParameters>
</asp:ObjectDataSource>

Examples
This section contains two code examples. The first code example shows how a GridView control can display data by using an ObjectDataSource object on an ASP.NET Web page. The second code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use. The following code example demonstrates how a GridView control can display data using an ObjectDataSource control on a Web Forms page. The ObjectDataSource identifies the partially or fully qualified class name of a business object with its TypeName property and a business object method that is called to retrieve data with its SelectMethod property. At run time, the object is created and the method is called using reflection. The GridView control enumerates through the IEnumerable collection that is returned by the SelectMethod property and displays the data.
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ObjectDataSource - Visual Basic Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.VB.EmployeeLogic" />
</form>
</body>
</html>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.CS.EmployeeLogic" />
</form>
</body>
</html>
The following code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use. The code example consists of the following two basic classes: The EmployeeLogic class, which is a stateless class that encapsulates business logic. The NorthwindEmployee class, which is a model class containing only the basic functionality that is required to load and persist data from the data tier.
An additional NorthwindDataException class is provided as a convenience. This set of example classes works with the Northwind Traders database, which is available with Microsoft SQL Server and Microsoft Access. For a complete working example, you must compile and use these classes with the Web Forms code examples that are provided. For information about how to install the Northwind Traders database, see How to: Install Sample Databases. This example is designed to be simple and easy to follow and to demonstrate one of the most common ways a business object interacts with an ObjectDataSource control. It is not a design recommendation. In some examples, additional methods are added to the EmployeeLogic or NorthwindEmployee classes, or modifications are made to this set of classes to demonstrate fundamental concepts.
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB
'
' EmployeeLogic is a stateless business object that encapsulates
' the operations you can perform on a NorthwindEmployee object.
' When the class is written in Visual Basic, you cannot use the Shared
' part.
Public Class EmployeeLogic
' Returns a collection of NorthwindEmployee objects.
Public Shared Function GetAllEmployees() As ICollection
Dim al As New ArrayList()
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim sds As New SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees")
Try
Dim IDs As IEnumerable = sds.Select(DataSourceSelectArguments.Empty)
' Iterate through the Enumeration and create a
' NorthwindEmployee object for each ID.
For Each row As DataRowView In IDs
Dim id As String = row("EmployeeID").ToString()
Dim nwe As New NorthwindEmployee(id)
' Add the NorthwindEmployee object to the collection.
al.Add(nwe)
Next
Finally
' If anything strange happens, clean up.
sds.Dispose()
End Try
Return al
End Function 'GetAllEmployees
Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
Return New NorthwindEmployee(anID)
End Function 'GetEmployee
Public Shared Sub UpdateEmployeeInfo(ne As NorthwindEmployee)
Dim retval As Boolean = ne.Save()
If Not retval Then
Throw New NorthwindDataException("UpdateEmployee failed.")
End If
End Sub 'UpdateEmployeeInfo
Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
End Sub 'DeleteEmployee
End Class 'EmployeeLogic
Public Class NorthwindEmployee
Public Sub New()
ID = DBNull.Value
aLastName = ""
aFirstName = ""
aTitle = ""
titleOfCourtesy = ""
reportsTo = - 1
End Sub 'New
Public Sub New(anID As Object)
Me.ID = anID
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim conn As New SqlConnection(cts.ConnectionString)
Dim sc As New SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " & _
" FROM Employees " & _
" WHERE EmployeeID = @empId", conn)
' Add the employee ID parameter and set its value.
sc.Parameters.Add(New SqlParameter("@empId", SqlDbType.Int)).Value = Int32.Parse(anID.ToString())
Dim sdr As SqlDataReader = Nothing
Try
conn.Open()
sdr = sc.ExecuteReader()
' This is not a while loop. It only loops once.
If Not (sdr Is Nothing) AndAlso sdr.Read() Then
' The IEnumerable contains DataRowView objects.
Me.aFirstName = sdr("FirstName").ToString()
Me.aLastName = sdr("LastName").ToString()
Me.aTitle = sdr("Title").ToString()
Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
If Not sdr.IsDBNull(4) Then
Me.reportsTo = sdr.GetInt32(4)
End If
Else
Throw New NorthwindDataException("Data not loaded for employee id.")
End If
Finally
Try
If Not (sdr Is Nothing) Then
sdr.Close()
End If
conn.Close()
Catch se As SqlException
' Log an event in the Application Event Log.
Throw
End Try
End Try
End Sub 'New
Private ID As Object
Private aLastName As String
Public Property LastName() As String
Get
Return aLastName
End Get
Set
aLastName = value
End Set
End Property
Private aFirstName As String
Public Property FirstName() As String
Get
Return aFirstName
End Get
Set
aFirstName = value
End Set
End Property
Private aTitle As String
Public Property Title() As String
Get
Return aTitle
End Get
Set
aTitle = value
End Set
End Property
Private titleOfCourtesy As String
Public Property Courtesy() As String
Get
Return titleOfCourtesy
End Get
Set
titleOfCourtesy = value
End Set
End Property
Private reportsTo As Integer
Public Property Supervisor() As Integer
Get
Return reportsTo
End Get
Set
reportsTo = value
End Set
End Property
Public Function Save() As Boolean
Return True
End Function 'Save
End Class 'NorthwindEmployee
Friend Class NorthwindDataException
Inherits Exception
Public Sub New(msg As String)
MyBase.New(msg)
End Sub 'New
End Class 'NorthwindDataException
End Namespace
namespace Samples.AspNet.CS {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic {
// Returns a collection of NorthwindEmployee objects.
public static ICollection GetAllEmployees () {
ArrayList al = new ArrayList();
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlDataSource sds
= new SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees");
try {
IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);
// Iterate through the Enumeration and create a
// NorthwindEmployee object for each ID.
foreach (DataRowView row in IDs) {
string id = row["EmployeeID"].ToString();
NorthwindEmployee nwe = new NorthwindEmployee(id);
// Add the NorthwindEmployee object to the collection.
al.Add(nwe);
}
}
finally {
// If anything strange happens, clean up.
sds.Dispose();
}
return al;
}
public static NorthwindEmployee GetEmployee(object anID) {
return new NorthwindEmployee(anID);
}
public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
bool retval = ne.Save();
if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
}
public static void DeleteEmployee(NorthwindEmployee ne) { }
}
public class NorthwindEmployee {
public NorthwindEmployee () {
ID = DBNull.Value;
lastName = "";
firstName = "";
title="";
titleOfCourtesy = "";
reportsTo = -1;
}
public NorthwindEmployee (object anID) {
this.ID = anID;
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlConnection conn = new SqlConnection (cts.ConnectionString);
SqlCommand sc =
new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
" FROM Employees " +
" WHERE EmployeeID = @empId",
conn);
// Add the employee ID parameter and set its value.
sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
SqlDataReader sdr = null;
try {
conn.Open();
sdr = sc.ExecuteReader();
// This is not a while loop. It only loops once.
if (sdr != null && sdr.Read()) {
// The IEnumerable contains DataRowView objects.
this.firstName = sdr["FirstName"].ToString();
this.lastName = sdr["LastName"].ToString();
this.title = sdr["Title"].ToString();
this.titleOfCourtesy = sdr["TitleOfCourtesy"].ToString();
if (! sdr.IsDBNull(4)) {
this.reportsTo = sdr.GetInt32(4);
}
}
else {
throw new NorthwindDataException("Data not loaded for employee id.");
}
}
finally {
try {
if (sdr != null) sdr.Close();
conn.Close();
}
catch (SqlException) {
// Log an event in the Application Event Log.
throw;
}
}
}
private object ID;
private string lastName;
public string LastName {
get { return lastName; }
set { lastName = value; }
}
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
private string title;
public String Title {
get { return title; }
set { title = value; }
}
private string titleOfCourtesy;
public string Courtesy {
get { return titleOfCourtesy; }
set { titleOfCourtesy = value; }
}
private int reportsTo;
public int Supervisor {
get { return reportsTo; }
set { reportsTo = value; }
}
public bool Save () {
return true;
}
}
internal class NorthwindDataException: Exception {
public NorthwindDataException(string msg) : base (msg) { }
}
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Bibliothèque de classes .NET Framework ObjectDataSource, classe Représente un objet métier qui fournit des données aux contrôles liés aux données dans des architectures multicouches d'application Web.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web (dans System.Web.dll)

Syntaxe
<ToolboxBitmapAttribute(GetType(ObjectDataSource))> _
Public Class ObjectDataSource _
Inherits DataSourceControl
[ToolboxBitmapAttribute(typeof(ObjectDataSource))]
public class ObjectDataSource : DataSourceControl
[ToolboxBitmapAttribute(typeof(ObjectDataSource))]
public ref class ObjectDataSource : public DataSourceControl
[<ToolboxBitmapAttribute(typeof(ObjectDataSource))>]
type ObjectDataSource =
class
inherit DataSourceControl
end
Le type ObjectDataSource expose les membres suivants.

Constructeurs

Propriétés
|
| Nom | Description |
|---|
.gif) | Adapter | Obtient l'adaptateur spécifique au navigateur pour le contrôle. (Hérité de Control.) | .gif) | AppRelativeTemplateSourceDirectory | Obtient ou définit le répertoire virtuel relatif à l'application de l'objet Page ou UserControl qui contient ce contrôle. (Hérité de Control.) | .gif) | BindingContainer | Infrastructure. Obtient le contrôle qui contient la liaison de données de ce contrôle. (Hérité de Control.) | .gif) | CacheDuration | Obtient ou définit la durée, en secondes, de la mise en cache des données par le contrôle de source de données avant que celles-ci soient récupérées par la propriété SelectMethod. | .gif) | CacheExpirationPolicy | Obtient ou définit le comportement d'expiration du cache qui, lorsqu'il est associé à la durée, décrit le comportement du cache utilisé par le contrôle de source de données. | .gif) | CacheKeyDependency | Obtient ou définit une dépendance de clé définie par l'utilisateur qui est liée à tous les objets du cache de données créés par le contrôle de source de données. | .gif) | ChildControlsCreated | Obtient une valeur qui indique si des contrôles enfants du contrôle serveur ont été créés. (Hérité de Control.) | .gif) | ClientID | Obtient l'identificateur de contrôle serveur généré par ASP.NET. (Hérité de DataSourceControl.) | .gif) | ClientIDMode | Cette propriété n'est pas utilisée pour les contrôles de source de données. (Hérité de DataSourceControl.) | .gif) | ClientIDSeparator | Obtient une valeur de caractère représentant le caractère de séparation utilisé dans la propriété ClientID. (Hérité de Control.) | .gif) | ConflictDetection | Obtient ou définit une valeur qui détermine si seules les nouvelles valeurs sont passées à la méthode Update ou si les anciennes et les nouvelles valeurs sont passées à la méthode Update. | .gif) | Context | Obtient l'objet HttpContext associé au contrôle serveur pour la demande Web en cours. (Hérité de Control.) | .gif) | Controls | Obtient un objet ControlCollection qui représente les contrôles enfants d'un contrôle serveur spécifié dans la hiérarchie de l'interface utilisateur. (Hérité de DataSourceControl.) | .gif) | ConvertNullToDBNull | Obtient ou définit une valeur indiquant si les valeurs Parameter qui sont passées à une opération de mise à jour, d'insertion ou de suppression sont automatiquement converties de la valeur nullNothingnullptrune référence null (Nothing en Visual Basic) à la valeur Value par le contrôle ObjectDataSource. | .gif) | DataItemContainer | Obtient une référence au conteneur d'attribution de noms si celui-ci implémente IDataItemContainer. (Hérité de Control.) | .gif) | DataKeysContainer | Obtient une référence au conteneur d'attribution de noms si celui-ci implémente IDataKeysControl. (Hérité de Control.) | .gif) | DataObjectTypeName | Obtient ou définit le nom d'une classe utilisée par le contrôle ObjectDataSource pour un paramètre dans une opération de mise à jour, d'insertion ou de suppression, au lieu de passer les valeurs individuelles du contrôle lié aux données. | .gif) | DeleteMethod | Obtient ou définit le nom de la méthode ou de la fonction que le contrôle ObjectDataSource appelle pour supprimer des données. | .gif) | DeleteParameters | Obtient la collection de paramètres qui contient les paramètres utilisés par la méthode DeleteMethod. | .gif) | DesignMode | Obtient une valeur indiquant si un contrôle est utilisé sur une aire de conception. (Hérité de Control.) | .gif) | EnableCaching | Obtient ou définit une valeur indiquant si la mise en cache de données du contrôle ObjectDataSource est activée. | .gif) | EnablePaging | Obtient ou définit une valeur qui indique si le contrôle de source de données prend en charge la pagination du groupe de données qu'il récupère. | .gif) | EnableTheming | Obtient une valeur indiquant si cet objet prend en charge des thèmes. (Hérité de DataSourceControl.) | .gif) | EnableViewState | Obtient ou définit une valeur indiquant si le contrôle serveur rend persistant son état d'affichage, ainsi que celui de tous les contrôles enfants qu'il contient, sur le client à l'origine de la demande. (Hérité de Control.) | .gif) | Events | Obtient la liste des délégués de gestionnaires d'événements pour le contrôle. Cette propriété est en lecture seule. (Hérité de Control.) | .gif) | FilterExpression | Obtient ou définit une expression de filtrage qui est appliquée lorsque la méthode spécifiée par la propriété SelectMethod est appelée. | .gif) | FilterParameters | Obtient une collection de paramètres qui sont associés aux espaces réservés des paramètres dans la chaîne FilterExpression. | .gif) | HasChildViewState | Obtient une valeur indiquant si les contrôles enfants du contrôle serveur en cours possèdent des paramètres d'état d'affichage enregistrés. (Hérité de Control.) | .gif) | ID | Obtient ou définit l'ID programmatique assigné au contrôle serveur. (Hérité de Control.) | .gif) | IdSeparator | Infrastructure. Obtient le caractère utilisé pour séparer des identificateurs de contrôle. (Hérité de Control.) | .gif) | InsertMethod | Obtient ou définit le nom de la méthode ou de la fonction que le contrôle ObjectDataSource appelle pour insérer des données. | .gif) | InsertParameters | Obtient la collection de paramètres qui contient les paramètres utilisés par la propriété InsertMethod. | .gif) | IsChildControlStateCleared | Obtient une valeur indiquant si les contrôles contenus dans ce contrôle utilisent l'état du contrôle. (Hérité de Control.) | .gif) | IsTrackingViewState | Obtient une valeur qui indique si le contrôle serveur enregistre les modifications apportées à son état d'affichage. (Hérité de Control.) | .gif) | IsViewStateEnabled | Obtient une valeur indiquant si l'état d'affichage est activé pour ce contrôle. (Hérité de Control.) | .gif) | LoadViewStateByID | Obtient une valeur indiquant si le contrôle participe au chargement de son état d'affichage par ID et non par index. (Hérité de Control.) | .gif) | MaximumRowsParameterName | Obtient ou définit le nom du paramètre de la méthode de récupération de l'objet métier qui est utilisé pour indiquer le nombre d'enregistrements à récupérer pour la prise en charge de la pagination de la source de données. | .gif) | NamingContainer | Obtient une référence au conteneur d'attribution de noms du contrôle serveur, qui crée un espace de noms unique pour différencier les contrôles serveur dont la propriété Control..::.ID possède la même valeur. (Hérité de Control.) | .gif) | OldValuesParameterFormatString | Obtient ou définit une chaîne de format à appliquer aux noms des paramètres des valeurs d'origine qui sont passées aux méthodes Delete ou Update. | .gif) | Page | Obtient une référence à l'instance de Page qui contient le contrôle serveur. (Hérité de Control.) | .gif) | Parent | Obtient une référence au contrôle parent du contrôle serveur dans la hiérarchie des contrôles de la page. (Hérité de Control.) | .gif) | RenderingCompatibility | Obtient une valeur qui spécifie la version ASP.NET avec laquelle le HTML restitué sera compatible. (Hérité de Control.) | .gif) | SelectCountMethod | Obtient ou définit le nom de la méthode ou de la fonction que le contrôle ObjectDataSource appelle pour récupérer un nombre de lignes. | .gif) | SelectMethod | Obtient ou définit le nom de la méthode ou de la fonction que le contrôle ObjectDataSource appelle pour récupérer des données. | .gif) | SelectParameters | Obtient une collection des paramètres utilisés par la méthode spécifiée par la propriété SelectMethod. | .gif) | Site | Obtient des informations sur le conteneur qui héberge le contrôle en cours lorsqu'il est rendu sur une aire de conception. (Hérité de Control.) | .gif) | SkinID | Obtient l'apparence à appliquer au contrôle DataSourceControl. (Hérité de DataSourceControl.) | .gif) | SortParameterName | Obtient ou définit le nom de l'objet métier utilisé par le paramètre SelectMethod pour spécifier une expression de tri pour la prise en charge du tri de la source de données. | .gif) | SqlCacheDependency | Obtient ou définit une chaîne délimitée par des points-virgules qui indique les bases de données et les tables à utiliser pour la dépendance de cache Microsoft SQL Server. | .gif) | StartRowIndexParameterName | Obtient ou définit le nom du paramètre de la méthode de récupération de données utilisé pour indiquer la valeur de l'identificateur du premier enregistrement à récupérer pour la prise en charge de la pagination de la source de données. | .gif) | TemplateControl | Obtient ou définit une référence au modèle qui contient ce contrôle. (Hérité de Control.) | .gif) | TemplateSourceDirectory | Obtient le répertoire virtuel du Page ou du UserControl qui contient le contrôle serveur en cours. (Hérité de Control.) | .gif) | TypeName | Obtient ou définit le nom de la classe que l'objet ObjectDataSource représente. | .gif) | UniqueID | Obtient l'identificateur unique qualifié sur le plan hiérarchique du contrôle serveur. (Hérité de Control.) | .gif) | UpdateMethod | Obtient ou définit le nom de la méthode ou de la fonction que le contrôle ObjectDataSource appelle pour mettre à jour des données. | .gif) | UpdateParameters | Obtient la collection de paramètres qui contient les paramètres utilisés par la méthode spécifiée par la propriété UpdateMethod. | .gif) | ViewState | Obtient un dictionnaire d'informations d'état qui vous permet d'enregistrer et de restaurer l'état d'affichage d'un contrôle serveur entre plusieurs demandes de la même page. (Hérité de Control.) | .gif) | ViewStateIgnoresCase | Obtient une valeur qui indique si l'objet StateBag respecte la casse. (Hérité de Control.) | .gif) | ViewStateMode | Obtient ou définit le mode d'état d'affichage de ce contrôle. (Hérité de Control.) | .gif) | Visible | Obtient ou définit une valeur indiquant l'affichage visuel ou non du contrôle. (Hérité de DataSourceControl.) | Début

Méthodes
|
| Nom | Description |
|---|
.gif) | AddedControl | Appelée après l'ajout d'un contrôle enfant à la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | AddParsedSubObject | Avertit le contrôle serveur qu'un élément XML ou HTML a été analysé et l'ajoute à l'objet ControlCollection du contrôle serveur. (Hérité de Control.) | .gif) | ApplyStyleSheetSkin | Applique les propriétés de style qui sont définies dans la feuille de style de la page au contrôle. (Hérité de DataSourceControl.) | .gif) | BuildProfileTree | Infrastructure. Collecte des informations sur le contrôle serveur et les livre à la propriété Trace à afficher lorsque le traçage est activé pour la page. (Hérité de Control.) | .gif) | ClearCachedClientID | Infrastructure. Affecte à la valeur ClientID mise en cache la valeur nullNothingnullptrune référence null (Nothing en Visual Basic). (Hérité de Control.) | .gif) | ClearChildControlState | Supprime les informations sur l'état du contrôle des contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildState | Supprime les informations sur l'état d'affichage et sur l'état du contrôle de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildViewState | Supprime les informations d'état d'affichage de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Affecte la valeur Inherit à la propriété ClientIDMode de l'instance de contrôle actuelle et de tous contrôles enfants. (Hérité de Control.) | .gif) | CreateChildControls | Appelé par l'infrastructure de page ASP.NET pour avertir les contrôles serveur qui utilisent une implémentation basée sur la composition qu'ils doivent créer tous les contrôles enfants qu'ils contiennent en préparation de la publication ou du rendu. (Hérité de Control.) | .gif) | CreateControlCollection | Crée une collection pour stocker des contrôles enfants. (Hérité de DataSourceControl.) | .gif) | DataBind()()() | Lie une source de données au contrôle serveur appelé et à tous ses contrôles enfants. (Hérité de Control.) | .gif) | DataBind(Boolean) | Lie une source de données au contrôle serveur appelé et tous ses contrôles enfants avec une option pour déclencher l'événement DataBinding. (Hérité de Control.) | .gif) | DataBindChildren | Lie une source de données aux contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | Delete | Exécute une opération de suppression en appelant la méthode identifiée par la propriété DeleteMethod avec tous les paramètres qui figurent dans la collection DeleteParameters. | .gif) | Dispose | Permet à un contrôle serveur d'effectuer le nettoyage final avant qu'il soit libéré de la mémoire. (Hérité de Control.) | .gif) | EnsureChildControls | Détermine si le contrôle serveur contient des contrôles enfants. S'il ne contient pas de contrôles enfants, il en crée. (Hérité de Control.) | .gif) | EnsureID | Crée un identificateur pour les contrôles auxquels aucun identificateur n'est assigné. (Hérité de Control.) | .gif) | Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) | .gif) | Finalize | Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.) | .gif) | FindControl(String) | Recherche un contrôle serveur possédant le paramètre id spécifié dans le conteneur d'attribution de noms actuel. (Hérité de DataSourceControl.) | .gif) | FindControl(String, Int32) | Infrastructure. Recherche le conteneur d'attribution de noms actuel d'un contrôle serveur avec l'id spécifié et un entier, spécifié dans le paramètre pathOffset, qui facilite la recherche. Vous ne devez pas substituer cette version de la méthode FindControl. (Hérité de Control.) | .gif) | Focus | Définit le focus d'entrée sur le contrôle. (Hérité de DataSourceControl.) | .gif) | GetDesignModeState | Infrastructure. Obtient les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) | .gif) | GetRouteUrl(Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) | .gif) | GetUniqueIDRelativeTo | Retourne la partie préfixée de la propriété UniqueID du contrôle spécifié. (Hérité de Control.) | .gif) | GetView | Récupère la vue de source de données associée au contrôle de source de données. (Substitue DataSourceControl..::.GetView(String).) | .gif) | GetViewNames | Récupère une collection des noms qui représentent la liste d'objets de vue associée à l'objet ObjectDataSource. (Substitue DataSourceControl..::.GetViewNames()()().) | .gif) | HasControls | Détermine si le contrôle serveur contient des contrôles enfants. (Hérité de DataSourceControl.) | .gif) | HasEvents | Retourne une valeur indiquant si des événements sont inscrits pour le contrôle ou des contrôles enfants. (Hérité de Control.) | .gif) | Insert | Exécute une opération d'insertion en appelant la méthode qui est identifiée par la propriété InsertMethod et tous les paramètres dans la collection InsertParameters. | .gif) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Restaure des informations sur l'état du contrôle à partir d'une demande de page antérieure enregistrée par la méthode SaveControlState. (Hérité de Control.) | .gif) | LoadViewState | Infrastructure. Charge l'état d'affichage précédemment enregistré du contrôle ObjectDataSource. (Substitue Control..::.LoadViewState(Object).) | .gif) | MapPathSecure | Récupère le chemin d'accès physique auquel un chemin d'accès virtuel, absolu ou relatif, correspond. (Hérité de Control.) | .gif) | MemberwiseClone | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) | .gif) | OnBubbleEvent | Détermine si l'événement pour le contrôle serveur est passé dans la hiérarchie des contrôles serveur de l'interface utilisateur de la page. (Hérité de Control.) | .gif) | OnDataBinding | Déclenche l'événement DataBinding. (Hérité de Control.) | .gif) | OnInit | Ajoute un gestionnaire d'événements LoadComplete à la page qui contient le contrôle ObjectDataSource. (Substitue Control..::.OnInit(EventArgs).) | .gif) | OnLoad | Déclenche l'événement Load. (Hérité de Control.) | .gif) | OnPreRender | Déclenche l'événement PreRender. (Hérité de Control.) | .gif) | OnUnload | Déclenche l'événement Unload. (Hérité de Control.) | .gif) | OpenFile | Obtient un Stream utilisé pour lire un fichier. (Hérité de Control.) | .gif) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RaiseDataSourceChangedEvent | Déclenche l'événement DataSourceChanged. (Hérité de DataSourceControl.) | .gif) | RemovedControl | Appelée après la suppression d'un contrôle enfant dans la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | Render | Envoie le contenu du contrôle serveur à un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderChildren | Renvoie le contenu des enfants d'un contrôle serveur dans un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderControl(HtmlTextWriter) | Renvoie le contenu du contrôle serveur dans un objet HtmlTextWriter fourni et stocke des informations de traçage au sujet du contrôle si le traçage est activé. (Hérité de DataSourceControl.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Génère le contenu du contrôle serveur dans un objet HtmlTextWriter à l'aide d'un objet ControlAdapter fourni. (Hérité de Control.) | .gif) | ResolveAdapter | Obtient l'adaptateur de contrôles responsable du rendu du contrôle spécifié. (Hérité de Control.) | .gif) | ResolveClientUrl | Obtient une URL qui peut être utilisée par le navigateur. (Hérité de Control.) | .gif) | ResolveUrl | Convertit une URL en une URL que le client soit en mesure d'utiliser. (Hérité de Control.) | .gif) | SaveControlState | Enregistre les modifications éventuellement apportées à l'état du contrôle serveur depuis la publication de la page sur le serveur. (Hérité de Control.) | .gif) | SaveViewState | Infrastructure. Enregistre l'état du contrôle ObjectDataSource. (Substitue Control..::.SaveViewState()()().) | .gif) | Select | Récupère les données du stockage de données sous-jacent en appelant la méthode qui est identifiée par la propriété SelectMethod avec les paramètres dans la collection SelectParameters. | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigne un délégué de gestionnaires d'événements pour générer le rendu du contrôle serveur et de son contenu dans son contrôle parent. (Hérité de Control.) | .gif) | ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) | .gif) | TrackViewState | Infrastructure. Suit les modifications d'état d'affichage apportées au contrôle ObjectDataSource afin de les stocker dans l'objet System.Web.UI..::.StateBag. (Substitue Control..::.TrackViewState()()().) | .gif) | Update | Exécute une opération de mise à jour en appelant la méthode identifiée par la propriété UpdateMethod et tous les paramètres qui figurent dans la collection UpdateParameters. | Début

Méthodes d'extension

Implémentations d'interface explicite
|
| Nom | Description |
|---|
.gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | Pour obtenir une description de ce membre, consultez IControlBuilderAccessor..::.ControlBuilder. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.GetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetOwnerControl. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.UserData. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.DataBindings. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.HasDataBindings. (Hérité de Control.) | .gif) .gif) | IDataSource..::.DataSourceChanged | Infrastructure. Se produit lorsqu'un contrôle de code source de données a changé d'une manière qui affecte des contrôles liés aux données. (Hérité de DataSourceControl.) | .gif) .gif) | IDataSource..::.GetView | Infrastructure. Obtient l'objet nommé DataSourceView associé au contrôle DataSourceControl. Certains contrôles de code source de données ne prennent en charge qu'un affichage, contrairement à d'autres qui en gèrent plusieurs. (Hérité de DataSourceControl.) | .gif) .gif) | IDataSource..::.GetViewNames | Infrastructure. Obtient une collection de noms, représentant la liste des objets DataSourceView associés au contrôle DataSourceControl. (Hérité de DataSourceControl.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.Expressions. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.HasExpressions. (Hérité de Control.) | .gif) .gif) | IListSource..::.ContainsListCollection | Infrastructure. Indique si le contrôle de code source de données est associé à une ou à plusieurs listes de données. (Hérité de DataSourceControl.) | .gif) .gif) | IListSource..::.GetList | Infrastructure. Obtient une liste des contrôles de code source de données qui peuvent être utilisés comme sources des listes de données. (Hérité de DataSourceControl.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | Début

Notes
Dans cette rubrique : IntroductionObjectDataSource est un contrôle de source de données ASP.NET qui représente un objet de couche intermédiaire lié aux bases de données ou un objet d'interface de données pour les contrôles liés aux données. Vous pouvez utiliser le contrôle ObjectDataSource conjointement à un contrôle lié aux données pour afficher, modifier et trier des données sur une page Web contenant un code court ou sans code. Il n'y a pas de rendu visuel du contrôle ObjectDataSource. Il est implémenté comme un contrôle. Vous pouvez donc le créer de manière déclarative et lui permettre éventuellement de participer à la gestion d'état. Par conséquent, ObjectDataSource ne prend pas en charge les fonctionnalités visuelles, telles que la propriété EnableTheming ou SkinID. ObjectifUne pratique de conception d'application très courante consiste à séparer la couche présentation de la logique métier et à encapsuler la logique métier dans les objets métier. Ces objets métier forment une couche distincte entre la couche présentation et la couche Données, constituant ainsi une architecture d'applications à trois couches. Le contrôle ObjectDataSource permet aux développeurs d'utiliser un contrôle de source de données ASP.NET tout en conservant leur architecture d'applications à trois couches. Le contrôle ObjectDataSource utilise la réflexion pour créer des instances d'objets métier et appeler des méthodes sur ces objets afin de récupérer, mettre à jour, insérer et supprimer des données. La propriété TypeName identifie le nom de la classe fonctionnant avec ObjectDataSource. Le contrôle ObjectDataSource crée et détruit une instance de la classe pour chaque appel à une méthode ; il ne garde pas l'objet en mémoire pendant la durée de vie de la requête Web. Cela constitue un facteur important si l'objet métier que vous utilisez requiert beaucoup de ressources ou si sa création et sa destruction coûtent cher. L'utilisation d'un objet coûteux ne peut pas provenir d'un choix de conception optimal, mais vous pouvez contrôler le cycle de vie de l'objet à l'aide des événements ObjectCreating, ObjectCreated et ObjectDisposing. Récupération de donnéesPour récupérer les données d'un objet métier, affectez à la propriété SelectMethod le nom de la méthode qui récupère les données. Si la méthode ne retourne pas d'objet IEnumerable ou DataSet, l'objet est encapsulé par l'exécution dans une collection IEnumerable. Si la signature de la méthode comporte des paramètres, vous pouvez ajouter des objets Parameter à la collection SelectParameters, puis les lier aux valeurs que vous souhaitez passer à la méthode spécifiée par la propriété SelectMethod. Pour que ObjectDataSource puisse utiliser les paramètres, ceux-ci doivent correspondre aux noms et types des paramètres dans la signature de la méthode. Pour plus d'informations, consultez Utilisation de paramètres avec le contrôle ObjectDataSource. Le contrôle ObjectDataSource récupère des données chaque fois que la méthode Select est appelée. Cette méthode fournit un accès par programme à la méthode spécifiée par la propriété SelectMethod. La méthode spécifiée par la propriété SelectMethod est appelée automatiquement par les contrôles liés au ObjectDataSource lorsque leur méthode DataBind est appelée. Si vous définissez la propriété DataSourceID d'un contrôle lié aux données, le contrôle crée automatiquement une liaison avec les données de la source de données, si nécessaire. La définition de la propriété DataSourceID est la méthode recommandée pour lier un contrôle ObjectDataSource à un contrôle lié aux données. Vous pouvez également définir la propriété DataSource, mais vous devrez ensuite appeler explicitement la méthode DataBind du contrôle lié aux données. Vous pouvez à tout moment appeler la méthode Select par programme pour récupérer des données. Pour plus d'informations sur la liaison de contrôles liés aux données à des contrôles de source de données, consultez Liaison à des données à l'aide d'un contrôle de source de données. Exécution d'opérations de donnéesSelon les fonctions de l'objet métier fonctionnant avec le contrôle ObjectDataSource, vous pouvez exécuter des opérations de données, telles que des mises à jour, des insertions et des suppressions. Pour exécuter ces opérations de données, définissez le nom de méthode approprié et tous les paramètres associés pour l'opération que vous souhaitez exécuter. Par exemple, pour une opération de mise à jour, affectez à la propriété UpdateMethod le nom de la méthode de l'objet métier qui effectue des mises à jour et ajoutez tous les paramètres requis à la collection UpdateParameters. Si le contrôle ObjectDataSource est associé à un contrôle lié aux données, les paramètres sont ajoutés par le contrôle lié aux données. Dans ce cas, vous devez vous assurer que les noms de paramètres de la méthode correspondent aux noms des champs du contrôle lié aux données. La mise à jour est effectuée lorsque la méthode Update est appelée, soit explicitement par votre code ou automatiquement par un contrôle lié aux données. Les opérations Delete et Insert suivent le même modèle général. Les objets métier sont supposés exécuter ces types d'opérations de données dans chaque enregistrement de manière individuelle, plutôt que par lots. Filtrage des donnéesLe contrôle ObjectDataSource peut filtrer les données récupérées par la propriété SelectMethod, si les données sont retournées en tant qu'objet DataSet ou DataTable. Le contrôle ObjectDataSource vous permet de mettre en cache tous les types de données, mais vous ne devez pas mettre en cache les objets qui conservent les ressources ou un état ne pouvant pas être partagés pour traiter plusieurs requêtes (par exemple, un objet SqlDataReader ouvert), parce que la même instance de l'objet sera utilisée pour traiter plusieurs requêtes. Vous pouvez affecter une expression de filtrage à la propriété FilterExpression à l'aide d'une syntaxe de chaîne de format et de valeurs de liaison dans l'expression aux paramètres spécifiés dans la collection FilterParameters. Mise en cacheObjectDataSource ne conserve pas l'instance de l'objet métier dans plusieurs requêtes, mais il peut mettre en cache le résultat de la propriété SelectMethod. Tandis que les données sont mises en cache, les appels suivants à la méthode Select retournent les données mises en cache au lieu de créer l'objet métier et appeler son SelectMethod à l'aide de la réflexion. La mise en cache vous permet d'éviter de créer l'objet et d'appeler sa méthode de données au détriment de la mémoire sur le serveur Web. ObjectDataSource met les données automatiquement en cache lorsque la propriété EnableCaching a la valeur true et lorsque la valeur de la propriété CacheDuration correspond au nombre de secondes pendant lesquelles le cache stocke les données avant d'être ignoré. Vous pouvez également spécifier une propriété CacheExpirationPolicy et éventuellement une propriété SqlCacheDependency. FonctionnalitésLe tableau suivant décrit les fonctionnalités du contrôle ObjectDataSource. Fonctionnalité | Spécifications |
|---|
Sélection | Affectez à la propriété SelectMethod le nom de la méthode de l'objet métier qui sélectionne les données et incluez tous les paramètres nécessaires dans la collection SelectParameters, soit par programme, soit en utilisant un contrôle lié aux données. | Tri | Affectez à la propriété SortParameterName le nom du paramètre dans la méthode SelectMethod qui retient les critères de tri. | Filtrage | Affectez à la propriété FilterExpression une expression de filtrage et ajoutez les paramètres éventuels à la collection FilterParameters pour filtrer les données lorsque la méthode Select est appelée. La méthode spécifiée par la propriété SelectMethod doit retourner DataSet ou DataTable. | Pagination | La pagination de source de données est prise en charge si la méthode SelectMethod contient les paramètres pour le nombre maximal d'enregistrements à récupérer et l'index du premier enregistrement à récupérer. Les noms de ces paramètres doivent être définis dans les propriétés MaximumRowsParameterName et StartRowIndexParameterName respectivement. Un contrôle lié aux données peut exécuter la pagination lui-même, même si le contrôle ObjectDataSource ne prend pas en charge la pagination directement dans la méthode spécifiée par la propriété SelectMethod. Pour que le contrôle lié aux données puisse exécuter la pagination, la méthode spécifiée par la propriété SelectMethod doit retourner un objet qui implémente l'interface ICollection. | Mise à jour | Affectez à la propriété UpdateMethod le nom de la méthode de l'objet métier qui met les données à jour et incluez tous les paramètres nécessaires dans la collection UpdateParameters. | Suppression | Affectez à la propriété DeleteMethod le nom de la méthode ou de la fonction d'objet métier qui supprime les données et incluez tous les paramètres nécessaires dans la collection DeleteParameters. | Insertion | Affectez à la propriété InsertMethod le nom de la méthode ou de la fonction d'objet métier qui insère les données et incluez tous les paramètres nécessaires dans la collection InsertParameters. | Mise en cache | Affectez la valeur true à la propriété EnableCaching, et définissez les propriétés CacheDuration et CacheExpirationPolicy selon le comportement de mise en cache de votre choix pour vos données mises en cache. |
Remarque |
|---|
Lorsque vous utilisez la classe ObjectDataSource pour mettre à jour ou insérer des données, les chaînes entrées au niveau du client ne sont pas converties automatiquement du format de la culture du client au format de la culture du serveur. Par exemple, la culture cliente peut spécifier DD/MM/YYYY comme format de date, et le format de date sur le serveur peut être des MMS/DD/YYYY. Dans ce cas, le 5 octobre 2009 sera entré dans un contrôle TextBox comme 5/10/2009 mais sera interprété comme le 10 mai 2009. Le 15 octobre 2009 serait entré comme 15/10/2009 et serait rejeté comme une date non valide. |
Vue de donnéesComme tous les contrôles de source de données, le contrôle ObjectDataSource est associé à une classe d'affichage de la source de données. Le contrôle ObjectDataSource correspond à l'interface utilisée par le développeur de pages pour traiter les données, tandis que la classe ObjectDataSourceView correspond à l'interface avec laquelle les contrôles liés aux données fonctionnent. En outre, la classe ObjectDataSourceView décrit les fonctions du contrôle de source de données et exécute le travail réel. Le contrôle ObjectDataSource n'est associé qu'à un ObjectDataSourceView et est toujours nommé DefaultView. Tandis que l'objet ObjectDataSourceView est exposé par la méthode GetView, nombre de ses propriétés et méthodes sont encapsulées et exposées directement par le contrôle ObjectDataSource. En arrière-plan, l'objet ObjectDataSourceView exécute toutes les opérations de données, y compris la récupération, l'insertion, la mise à jour, la suppression, le filtrage et le tri des données. Pour plus d'informations, consultez ObjectDataSourceView. Utilisation de LINQ to SQLVous pouvez utiliser le contrôle ObjectDataSource avec une classe LINQ to SQL. Pour ce faire, affectez le nom de la classe de contexte de données à la propriété TypeName. Vous pouvez également affecter les méthodes SelectMethod, UpdateMethod, InsertMethod et DeleteMethod aux méthodes de la classe de contexte de données qui effectuent les opérations correspondantes. Vous devez créer un gestionnaire d'événements pour l'événement ObjectDisposing afin d'annuler la suppression de la classe de contexte de données. Cette étape est nécessaire car la classe LINQ to SQL prend en charge l'exécution différée, tandis que le contrôle ObjectDataSource tente de supprimer le contexte de données après l'opération Select. Pour plus d'informations sur la création des classes LINQ to SQL, consultez Comment : créer des classes LINQ to SQL dans un projet Web. Pour un exemple d'annulation de la suppression d'une classe de contexte de données, consultez l'événement ObjectDisposing. Syntaxe déclarative
<asp:ObjectDataSource
CacheDuration="string|Infinite"
CacheExpirationPolicy="Absolute|Sliding"
CacheKeyDependency="string"
ConflictDetection="OverwriteChanges|CompareAllValues"
ConvertNullToDBNull="True|False"
DataObjectTypeName="string"
DeleteMethod="string"
EnableCaching="True|False"
EnablePaging="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
FilterExpression="string"
ID="string"
InsertMethod="string"
MaximumRowsParameterName="string"
OldValuesParameterFormatString="string"
OnDataBinding="DataBinding event handler"
OnDeleted="Deleted event handler"
OnDeleting="Deleting event handler"
OnDisposed="Disposed event handler"
OnFiltering="Filtering event handler"
OnInit="Init event handler"
OnInserted="Inserted event handler"
OnInserting="Inserting event handler"
OnLoad="Load event handler"
OnObjectCreated="ObjectCreated event handler"
OnObjectCreating="ObjectCreating event handler"
OnObjectDisposing="ObjectDisposing event handler"
OnPreRender="PreRender event handler"
OnSelected="Selected event handler"
OnSelecting="Selecting event handler"
OnUnload="Unload event handler"
OnUpdated="Updated event handler"
OnUpdating="Updating event handler"
runat="server"
SelectCountMethod="string"
SelectMethod="string"
SkinID="string"
SortParameterName="string"
SqlCacheDependency="string"
StartRowIndexParameterName="string"
TypeName="string"
UpdateMethod="string"
Visible="True|False"
>
<DeleteParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</DeleteParameters>
<FilterParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</FilterParameters>
<InsertParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</InsertParameters>
<SelectParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter
ControlID="string"
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:CookieParameter
ConvertEmptyStringToNull="True|False"
CookieName="string"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:FormParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
FormField="string"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:Parameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:ProfileParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
PropertyName="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:QueryStringParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
QueryStringField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
<asp:SessionParameter
ConvertEmptyStringToNull="True|False"
DefaultValue="string"
Direction="Input|Output|InputOutput|ReturnValue"
Name="string"
SessionField="string"
Size="integer"
Type="Empty|Object|DBNull|Boolean|Char|SByte|
Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
Single|Double|Decimal|DateTime|String"
/>
</UpdateParameters>
</asp:ObjectDataSource>

Exemples
Cette section comprend deux exemples de code. Le premier exemple de code montre comment un contrôle GridView peut afficher des données à l'aide d'un objet ObjectDataSource sur une page Web ASP.NET. Le deuxième exemple de code fournit un exemple d'objet métier de couche intermédiaire utilisé par cet exemple de code ObjectDataSource et de nombreux autres. L'exemple de code suivant montre comment un contrôle GridView peut afficher des données à l'aide d'un contrôle ObjectDataSource sur une page Web Forms. ObjectDataSource identifie le nom de classe qualifié complet ou partiel d'un objet métier avec sa propriété TypeName et une méthode d'objet métier qui sont appelées pour récupérer des données avec sa propriété SelectMethod. Au moment de l'exécution, l'objet est créé et la méthode est appelée par réflexion. Le contrôle GridView effectue une énumération de la collection IEnumerable retournée par la propriété SelectMethod, puis affiche les données.
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ObjectDataSource - Visual Basic Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.VB.EmployeeLogic" />
</form>
</body>
</html>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.CS.EmployeeLogic" />
</form>
</body>
</html>
L'exemple de code suivant fournit un exemple d'objet métier de couche intermédiaire utilisé par cet exemple de code ObjectDataSource et de nombreux autres. L'exemple de code se compose des deux classes de base suivantes : Classe EmployeeLogic, qui est une classe sans état qui encapsule la logique métier. La classe NorthwindEmployee, qui est une classe du modèle contenant uniquement les fonctionnalités de base requises pour charger et rendre persistantes des données de la couche Données.
Une classe NorthwindDataException supplémentaire est fournie dans un but pratique. Cet ensemble d'exemples de classes fonctionne avec la base de données Northwind Traders disponible avec Microsoft SQL Server et Microsoft Access. Pour obtenir un exemple complet, vous devez compiler et utiliser ces classes avec les exemples de code Web Forms fournis. Pour plus d'informations sur l'installation de la base de données Northwind Traders, consultez Comment : installer des exemples de bases de données. Cet exemple est conçu pour être simple à suivre et pour illustrer l'une des interactions les plus courantes entre un objet métier et un contrôle ObjectDataSource. Il ne s'agit pas d'une recommandation de conception. Dans certains exemples, des méthodes supplémentaires sont ajoutées aux classes EmployeeLogic ou NorthwindEmployee, ou des modifications sont apportées à ce jeu de classes pour illustrer les concepts fondamentaux.
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB
'
' EmployeeLogic is a stateless business object that encapsulates
' the operations you can perform on a NorthwindEmployee object.
' When the class is written in Visual Basic, you cannot use the Shared
' part.
Public Class EmployeeLogic
' Returns a collection of NorthwindEmployee objects.
Public Shared Function GetAllEmployees() As ICollection
Dim al As New ArrayList()
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim sds As New SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees")
Try
Dim IDs As IEnumerable = sds.Select(DataSourceSelectArguments.Empty)
' Iterate through the Enumeration and create a
' NorthwindEmployee object for each ID.
For Each row As DataRowView In IDs
Dim id As String = row("EmployeeID").ToString()
Dim nwe As New NorthwindEmployee(id)
' Add the NorthwindEmployee object to the collection.
al.Add(nwe)
Next
Finally
' If anything strange happens, clean up.
sds.Dispose()
End Try
Return al
End Function 'GetAllEmployees
Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
Return New NorthwindEmployee(anID)
End Function 'GetEmployee
Public Shared Sub UpdateEmployeeInfo(ne As NorthwindEmployee)
Dim retval As Boolean = ne.Save()
If Not retval Then
Throw New NorthwindDataException("UpdateEmployee failed.")
End If
End Sub 'UpdateEmployeeInfo
Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
End Sub 'DeleteEmployee
End Class 'EmployeeLogic
Public Class NorthwindEmployee
Public Sub New()
ID = DBNull.Value
aLastName = ""
aFirstName = ""
aTitle = ""
titleOfCourtesy = ""
reportsTo = - 1
End Sub 'New
Public Sub New(anID As Object)
Me.ID = anID
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim conn As New SqlConnection(cts.ConnectionString)
Dim sc As New SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " & _
" FROM Employees " & _
" WHERE EmployeeID = @empId", conn)
' Add the employee ID parameter and set its value.
sc.Parameters.Add(New SqlParameter("@empId", SqlDbType.Int)).Value = Int32.Parse(anID.ToString())
Dim sdr As SqlDataReader = Nothing
Try
conn.Open()
sdr = sc.ExecuteReader()
' This is not a while loop. It only loops once.
If Not (sdr Is Nothing) AndAlso sdr.Read() Then
' The IEnumerable contains DataRowView objects.
Me.aFirstName = sdr("FirstName").ToString()
Me.aLastName = sdr("LastName").ToString()
Me.aTitle = sdr("Title").ToString()
Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
If Not sdr.IsDBNull(4) Then
Me.reportsTo = sdr.GetInt32(4)
End If
Else
Throw New NorthwindDataException("Data not loaded for employee id.")
End If
Finally
Try
If Not (sdr Is Nothing) Then
sdr.Close()
End If
conn.Close()
Catch se As SqlException
' Log an event in the Application Event Log.
Throw
End Try
End Try
End Sub 'New
Private ID As Object
Private aLastName As String
Public Property LastName() As String
Get
Return aLastName
End Get
Set
aLastName = value
End Set
End Property
Private aFirstName As String
Public Property FirstName() As String
Get
Return aFirstName
End Get
Set
aFirstName = value
End Set
End Property
Private aTitle As String
Public Property Title() As String
Get
Return aTitle
End Get
Set
aTitle = value
End Set
End Property
Private titleOfCourtesy As String
Public Property Courtesy() As String
Get
Return titleOfCourtesy
End Get
Set
titleOfCourtesy = value
End Set
End Property
Private reportsTo As Integer
Public Property Supervisor() As Integer
Get
Return reportsTo
End Get
Set
reportsTo = value
End Set
End Property
Public Function Save() As Boolean
Return True
End Function 'Save
End Class 'NorthwindEmployee
Friend Class NorthwindDataException
Inherits Exception
Public Sub New(msg As String)
MyBase.New(msg)
End Sub 'New
End Class 'NorthwindDataException
End Namespace
namespace Samples.AspNet.CS {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic {
// Returns a collection of NorthwindEmployee objects.
public static ICollection GetAllEmployees () {
ArrayList al = new ArrayList();
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlDataSource sds
= new SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees");
try {
IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);
// Iterate through the Enumeration and create a
// NorthwindEmployee object for each ID.
foreach (DataRowView row in IDs) {
string id = row["EmployeeID"].ToString();
NorthwindEmployee nwe = new NorthwindEmployee(id);
// Add the NorthwindEmployee object to the collection.
al.Add(nwe);
}
}
finally {
// If anything strange happens, clean up.
sds.Dispose();
}
return al;
}
public static NorthwindEmployee GetEmployee(object anID) {
return new NorthwindEmployee(anID);
}
public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
bool retval = ne.Save();
if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
}
public static void DeleteEmployee(NorthwindEmployee ne) { }
}
public class NorthwindEmployee {
public NorthwindEmployee () {
ID = DBNull.Value;
lastName = "";
firstName = "";
title="";
titleOfCourtesy = "";
reportsTo = -1;
}
public NorthwindEmployee (object anID) {
this.ID = anID;
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlConnection conn = new SqlConnection (cts.ConnectionString);
SqlCommand sc =
new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
" FROM Employees " +
" WHERE EmployeeID = @empId",
conn);
// Add the employee ID parameter and set its value.
sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
SqlDataReader sdr = null;
try {
conn.Open();
sdr = sc.ExecuteReader();
// This is not a while loop. It only loops once.
if (sdr != null && sdr.Read()) {
// The IEnumerable contains DataRowView objects.
this.firstName = sdr["FirstName"].ToString();
this.lastName = sdr["LastName"].ToString();
this.title = sdr["Title"].ToString();
this.titleOfCourtesy = sdr["TitleOfCourtesy"].ToString();
if (! sdr.IsDBNull(4)) {
this.reportsTo = sdr.GetInt32(4);
}
}
else {
throw new NorthwindDataException("Data not loaded for employee id.");
}
}
finally {
try {
if (sdr != null) sdr.Close();
conn.Close();
}
catch (SqlException) {
// Log an event in the Application Event Log.
throw;
}
}
}
private object ID;
private string lastName;
public string LastName {
get { return lastName; }
set { lastName = value; }
}
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
private string title;
public String Title {
get { return title; }
set { title = value; }
}
private string titleOfCourtesy;
public string Courtesy {
get { return titleOfCourtesy; }
set { titleOfCourtesy = value; }
}
private int reportsTo;
public int Supervisor {
get { return reportsTo; }
set { reportsTo = value; }
}
public bool Save () {
return true;
}
}
internal class NorthwindDataException: Exception {
public NorthwindDataException(string msg) : base (msg) { }
}
}

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
RéférenceAutres ressources
|