Duration (Pacific Standard Time):
To (Pacific Standard Time):
Impact:
User Action:
.NET Framework Class Library

ObjectDataSource Class

Represents a business object that provides data to data-bound controls in multitier Web application architectures.

System.Object
  System.Web.UI.Control
    System.Web.UI.DataSourceControl
      System.Web.UI.WebControls.ObjectDataSource

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
<ToolboxBitmapAttribute(GetType(ObjectDataSource))> _
Public Class ObjectDataSource _
	Inherits DataSourceControl
<asp:ObjectDataSource />

The ObjectDataSource type exposes the following members.

  Name Description
Public method ObjectDataSource() Initializes a new instance of the ObjectDataSource class.
Public method ObjectDataSource(String, String) Initializes a new instance of the ObjectDataSource class with the specified type name and data retrieval method name.
Top
  Name Description
Protected property Adapter Gets the browser-specific adapter for the control. (Inherited from Control.)
Public property AppRelativeTemplateSourceDirectory Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control. (Inherited from Control.)
Public property BindingContainer Infrastructure. Gets the control that contains this control's data binding. (Inherited from Control.)
Public property CacheDuration Gets or sets the length of time, in seconds, that the data source control caches data that is retrieved by the SelectMethod property.
Public property 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.
Public property 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.
Protected property ChildControlsCreated Gets a value that indicates whether the server control's child controls have been created. (Inherited from Control.)
Public property ClientID Gets the server control identifier generated by ASP.NET. (Inherited from DataSourceControl.)
Public property ClientIDMode This property is not used for data source controls. (Inherited from DataSourceControl.)
Protected property ClientIDSeparator Gets a character value representing the separator character used in the ClientID property. (Inherited from Control.)
Public property 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.
Protected property Context Gets the HttpContext object associated with the server control for the current Web request. (Inherited from Control.)
Public property Controls Gets a ControlCollection object that represents the child controls for a specified server control in the UI hierarchy. (Inherited from DataSourceControl.)
Public property 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 null to the Value value by the ObjectDataSource control.
Public property DataItemContainer Gets a reference to the naming container if the naming container implements IDataItemContainer. (Inherited from Control.)
Public property DataKeysContainer Gets a reference to the naming container if the naming container implements IDataKeysControl. (Inherited from Control.)
Public property 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.
Public property DeleteMethod Gets or sets the name of the method or function that the ObjectDataSource control invokes to delete data.
Public property DeleteParameters Gets the parameters collection that contains the parameters that are used by the DeleteMethod method.
Protected property DesignMode Gets a value indicating whether a control is being used on a design surface. (Inherited from Control.)
Public property EnableCaching Gets or sets a value indicating whether the ObjectDataSource control has data caching enabled.
Public property EnablePaging Gets or sets a value that indicates whether the data source control supports paging through the set of data that it retrieves.
Public property EnableTheming Gets a value indicating whether this control supports themes. (Inherited from DataSourceControl.)
Public property 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.)
Protected property Events Gets a list of event handler delegates for the control. This property is read-only. (Inherited from Control.)
Public property FilterExpression Gets or sets a filtering expression that is applied when the method that is specified by the SelectMethod property is called.
Public property FilterParameters Gets a collection of parameters that are associated with any parameter placeholders in the FilterExpression string.
Protected property HasChildViewState Gets a value indicating whether the current server control's child controls have any saved view-state settings. (Inherited from Control.)
Public property ID Gets or sets the programmatic identifier assigned to the server control. (Inherited from Control.)
Protected property IdSeparator Infrastructure. Gets the character used to separate control identifiers. (Inherited from Control.)
Public property InsertMethod Gets or sets the name of the method or function that the ObjectDataSource control invokes to insert data.
Public property InsertParameters Gets the parameters collection that contains the parameters that are used by the InsertMethod property.
Protected property IsChildControlStateCleared Gets a value indicating whether controls contained within this control have control state. (Inherited from Control.)
Protected property IsTrackingViewState Gets a value that indicates whether the server control is saving changes to its view state. (Inherited from Control.)
Protected property IsViewStateEnabled Gets a value indicating whether view state is enabled for this control. (Inherited from Control.)
Protected property LoadViewStateByID Gets a value indicating whether the control participates in loading its view state by ID instead of index. (Inherited from Control.)
Public property 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.
Public property 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.)
Public property 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.
Public property Page Gets a reference to the Page instance that contains the server control. (Inherited from Control.)
Public property Parent Gets a reference to the server control's parent control in the page control hierarchy. (Inherited from Control.)
Public property ParsingCulture Gets a or sets a value that indicates what culture information is used when converting string values to actual property types in order to construct an object of the type indicated by DataObjectTypeName.
Public property RenderingCompatibility Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with. (Inherited from Control.)
Public property SelectCountMethod Gets or sets the name of the method or function that the ObjectDataSource control invokes to retrieve a row count.
Public property SelectMethod Gets or sets the name of the method or function that the ObjectDataSource control invokes to retrieve data.
Public property SelectParameters Gets a collection of parameters that are used by the method specified by the SelectMethod property.
Public property Site Gets information about the container that hosts the current control when rendered on a design surface. (Inherited from Control.)
Public property SkinID Gets the skin to apply to the DataSourceControl control. (Inherited from DataSourceControl.)
Public property 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.
Public property SqlCacheDependency Gets or sets a semicolon-delimited string that indicates which databases and tables to use for the Microsoft SQL Server cache dependency.
Public property 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.
Public property TemplateControl Gets or sets a reference to the template that contains this control. (Inherited from Control.)
Public property TemplateSourceDirectory Gets the virtual directory of the Page or UserControl that contains the current server control. (Inherited from Control.)
Public property TypeName Gets or sets the name of the class that the ObjectDataSource object represents.
Public property UniqueID Gets the unique, hierarchically qualified identifier for the server control. (Inherited from Control.)
Public property UpdateMethod Gets or sets the name of the method or function that the ObjectDataSource control invokes to update data.
Public property UpdateParameters Gets the parameters collection that contains the parameters that are used by the method that is specified by the UpdateMethod property.
Public property ValidateRequestMode Gets or sets a value that indicates whether the control checks client input from the browser for potentially dangerous values. (Inherited from Control.)
Protected property 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.)
Protected property ViewStateIgnoresCase Gets a value that indicates whether the StateBag object is case-insensitive. (Inherited from Control.)
Public property ViewStateMode Gets or sets the view-state mode of this control. (Inherited from Control.)
Public property Visible Gets or sets a value indicating whether the control is visually displayed. (Inherited from DataSourceControl.)
Top
  Name Description
Protected method AddedControl Called after a child control is added to the Controls collection of the Control object. (Inherited from Control.)
Protected method 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.)
Public method ApplyStyleSheetSkin Applies the style properties that are defined in the page style sheet to the control. (Inherited from DataSourceControl.)
Protected method BeginRenderTracing Begins design-time tracing of rendering data. (Inherited from Control.)
Protected method 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.)
Protected method ClearCachedClientID Infrastructure. Sets the cached ClientID value to null. (Inherited from Control.)
Protected method ClearChildControlState Deletes the control-state information for the server control's child controls. (Inherited from Control.)
Protected method ClearChildState Deletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.)
Protected method ClearChildViewState Deletes the view-state information for all the server control's child controls. (Inherited from Control.)
Protected method ClearEffectiveClientIDMode Infrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.)
Protected method 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.)
Protected method CreateControlCollection Creates a collection to store child controls. (Inherited from DataSourceControl.)
Public method DataBind() Binds a data source to the invoked server control and all its child controls. (Inherited from Control.)
Protected method 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.)
Protected method DataBindChildren Binds a data source to the server control's child controls. (Inherited from Control.)
Public method 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.
Public method Dispose Enables a server control to perform final clean up before it is released from memory. (Inherited from Control.)
Protected method EndRenderTracing Ends design-time tracing of rendering data. (Inherited from Control.)
Protected method EnsureChildControls Determines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.)
Protected method EnsureID Creates an identifier for controls that do not have an identifier assigned. (Inherited from Control.)
Public method Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method FindControl(String) Searches the current naming container for a server control with the specified id parameter. (Inherited from DataSourceControl.)
Protected method 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.)
Public method Focus Sets input focus to the control. (Inherited from DataSourceControl.)
Protected method GetDesignModeState Infrastructure. Gets design-time data for a control. (Inherited from Control.)
Public method GetHashCode Serves as the default hash function. (Inherited from Object.)
Public method GetRouteUrl(Object) Gets the URL that corresponds to a set of route parameters. (Inherited from Control.)
Public method GetRouteUrl(RouteValueDictionary) Gets the URL that corresponds to a set of route parameters. (Inherited from Control.)
Public method GetRouteUrl(String, Object) Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.)
Public method GetRouteUrl(String, RouteValueDictionary) Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method GetUniqueIDRelativeTo Returns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.)
Protected method GetView Retrieves the named data source view that is associated with the data source control. (Overrides DataSourceControl.GetView(String).)
Protected method GetViewNames Retrieves a collection of names representing the list of view objects that are associated with the ObjectDataSource object. (Overrides DataSourceControl.GetViewNames().)
Public method HasControls Determines if the server control contains any child controls. (Inherited from DataSourceControl.)
Protected method HasEvents Returns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.)
Public method Insert Performs an insert operation by calling the method that is identified by the InsertMethod property and any parameters in the InsertParameters collection.
Protected method IsLiteralContent Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.)
Protected method LoadControlState Restores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.)
Protected method LoadViewState Infrastructure. Loads the previously saved view state of the ObjectDataSource control. (Overrides Control.LoadViewState(Object).)
Protected method MapPathSecure Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method OnBubbleEvent Determines whether the event for the server control is passed up the page's UI server control hierarchy. (Inherited from Control.)
Protected method OnDataBinding Raises the DataBinding event. (Inherited from Control.)
Protected method OnInit Adds a LoadComplete event handler to the page that contains the ObjectDataSource control. (Overrides Control.OnInit(EventArgs).)
Protected method OnLoad Raises the Load event. (Inherited from Control.)
Protected method OnPreRender Raises the PreRender event. (Inherited from Control.)
Protected method OnUnload Raises the Unload event. (Inherited from Control.)
Protected method OpenFile Gets a Stream used to read a file. (Inherited from Control.)
Protected method RaiseBubbleEvent Assigns any sources of the event and its information to the control's parent. (Inherited from Control.)
Protected method RaiseDataSourceChangedEvent Raises the DataSourceChanged event. (Inherited from DataSourceControl.)
Protected method RemovedControl Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.)
Protected method Render Sends server control content to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.)
Protected method 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.)
Public method 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.)
Protected method RenderControl(HtmlTextWriter, ControlAdapter) Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.)
Protected method ResolveAdapter Gets the control adapter responsible for rendering the specified control. (Inherited from Control.)
Public method ResolveClientUrl Gets a URL that can be used by the browser. (Inherited from Control.)
Public method ResolveUrl Converts a URL into one that is usable on the requesting client. (Inherited from Control.)
Protected method SaveControlState Saves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.)
Protected method SaveViewState Infrastructure. Saves the state of the ObjectDataSource control. (Overrides Control.SaveViewState().)
Public method 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.
Protected method SetDesignModeState Sets design-time data for a control. (Inherited from Control.)
Public method SetRenderMethodDelegate Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.)
Public method SetTraceData(Object, Object) Sets trace data for design-time tracing of rendering data, using the trace data key and the trace data value. (Inherited from Control.)
Public method SetTraceData(Object, Object, Object) Sets trace data for design-time tracing of rendering data, using the traced object, the trace data key, and the trace data value. (Inherited from Control.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Protected method 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().)
Public method 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
  Name Description
Public event DataBinding Occurs when the server control binds to a data source. (Inherited from Control.)
Public event Deleted Occurs when a Delete operation has completed.
Public event Deleting Occurs before a Delete operation.
Public event Disposed Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested. (Inherited from Control.)
Public event Filtering Occurs before a filter operation.
Public event Init Occurs when the server control is initialized, which is the first step in its lifecycle. (Inherited from Control.)
Public event Inserted Occurs when an Insert operation has completed.
Public event Inserting Occurs before an Insert operation.
Public event Load Occurs when the server control is loaded into the Page object. (Inherited from Control.)
Public event ObjectCreated Occurs after the object that is identified by the TypeName property is created.
Public event ObjectCreating Occurs before the object that is identified by the TypeName property is created.
Public event ObjectDisposing Occurs before the object that is identified by the TypeName property is discarded.
Public event PreRender Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.)
Public event Selected Occurs when a Select operation has completed.
Public event Selecting Occurs before a Select operation.
Public event Unload Occurs when the server control is unloaded from memory. (Inherited from Control.)
Public event Updated Occurs when an Update operation has completed.
Public event Updating Occurs before an Update operation.
Top
  Name Description
Public Extension Method FindDataSourceControl Returns the data source that is associated with the data control for the specified control. (Defined by DynamicDataExtensions.)
Public Extension Method FindFieldTemplate Returns the field template for the specified column in the specified control's naming container. (Defined by DynamicDataExtensions.)
Public Extension Method FindMetaTable Returns the metatable object for the containing data control. (Defined by DynamicDataExtensions.)
Top
  Name Description
Explicit interface implemetation Private property IControlBuilderAccessor.ControlBuilder For a description of this member, see IControlBuilderAccessor.ControlBuilder. (Inherited from Control.)
Explicit interface implemetation Private method IControlDesignerAccessor.GetDesignModeState For a description of this member, see IControlDesignerAccessor.GetDesignModeState. (Inherited from Control.)
Explicit interface implemetation Private method IControlDesignerAccessor.SetDesignModeState For a description of this member, see IControlDesignerAccessor.SetDesignModeState. (Inherited from Control.)
Explicit interface implemetation Private method IControlDesignerAccessor.SetOwnerControl Infrastructure. For a description of this member, see IControlDesignerAccessor.SetOwnerControl. (Inherited from Control.)
Explicit interface implemetation Private property IControlDesignerAccessor.UserData For a description of this member, see IControlDesignerAccessor.UserData. (Inherited from Control.)
Explicit interface implemetation Private property IDataBindingsAccessor.DataBindings For a description of this member, see IDataBindingsAccessor.DataBindings. (Inherited from Control.)
Explicit interface implemetation Private property IDataBindingsAccessor.HasDataBindings For a description of this member, see IDataBindingsAccessor.HasDataBindings. (Inherited from Control.)
Explicit interface implemetation Private event IDataSource.DataSourceChanged Infrastructure. Occurs when a data source control has changed in a way that affects data-bound controls. (Inherited from DataSourceControl.)
Explicit interface implemetation Private method 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.)
Explicit interface implemetation Private method IDataSource.GetViewNames Infrastructure. Gets a collection of names, representing the list of DataSourceView objects associated with the DataSourceControl control. (Inherited from DataSourceControl.)
Explicit interface implemetation Private property IExpressionsAccessor.Expressions For a description of this member, see IExpressionsAccessor.Expressions. (Inherited from Control.)
Explicit interface implemetation Private property IExpressionsAccessor.HasExpressions For a description of this member, see IExpressionsAccessor.HasExpressions. (Inherited from Control.)
Explicit interface implemetation Private property IListSource.ContainsListCollection Infrastructure. Indicates whether the data source control is associated with one or more lists of data. (Inherited from DataSourceControl.)
Explicit interface implemetation Private method IListSource.GetList Infrastructure. Gets a list of data source controls that can be used as sources of lists of data. (Inherited from DataSourceControl.)
Explicit interface implemetation Private method IParserAccessor.AddParsedSubObject For a description of this member, see IParserAccessor.AddParsedSubObject. (Inherited from Control.)
Top

In this topic:

Introduction

An ObjectDataSource control works with a class that you create. You create methods that retrieve and update data, and you provide the names of those methods to the ObjectDataSource control in markup. During rendering or postback processing, the ObjectDataSource calls the methods that you have specified.

There is no visual rendering of the ObjectDataSource control. As a result, the ObjectDataSource does not support visual features such as the EnableTheming or SkinID property.

Purpose

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

Note Note

The methods that are identified by the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod properties can be instance methods or static (Shared in Visual Basic) methods. If the methods are static (Shared in Visual Basic), an instance of the business object is not created, and the ObjectCreating, ObjectCreated, and ObjectDisposing events are not raised.

Retrieving Data

To retrieve data from a business object, set the SelectMethod property to 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 control 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 Operations

Depending 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 parameter 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 Data

The ObjectDataSource control can filter data that is retrieved by the SelectMethod property, if the data is returned as a DataSet or DataTable object. 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.

Caching

Although the ObjectDataSource does not retain the instance of the business object across multiple requests, it can cache the result of calling the method identified by 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. 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.

Features

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

As 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 SQL

You 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 Project. For an example of how to cancel the disposing of a data context class, see the ObjectDisposing event.

Using the Entity Framework

You can also use the ObjectDataSource control with the Entity Framework. For more information, see Using the Entity Framework and the ObjectDataSource Control.

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>
Topic Location
How to: Bind to Data in a Templated Control Building ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source Controls Building ASP .NET Web Applications
How to: Bind to Data in a Templated Control Building ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source Controls Building ASP .NET Web Applications
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component Building ASP .NET Web Applications in Visual Studio
How To: Secure Connection Strings when Using Data Source Controls (Visual Studio) Building ASP .NET Web Applications in Visual Studio
How to: Add Repeater Web Server Controls to a Web Forms Page (Visual Studio) Building ASP .NET Web Applications in Visual Studio
Walkthrough: Data Binding to a Custom Business Object Building ASP .NET Web Applications in Visual Studio
How to: Bind to Data in a Templated Control in Visual Studio Building ASP .NET Web Applications in Visual Studio
Walkthrough: Using the ObjectDataSource with an XML File

A Visual Studio Web site project with source code is available to accompany this topic: Download.

This section shows an ObjectDataSource in markup in an .aspx page and it shows the business objects that it works with. The example is the .aspx page. It contains a GridView control that is bound to an ObjectDataSource control. The ObjectDataSource control markup specifies the name of the business object and the name of the business object method to call in order to retrieve data.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <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>

The following example shows the business object that the ObjectDataSource control in the .aspx page uses. (Many other ObjectDataSource code examples use this business object also.) The example consists of the following two basic classes:

  • The EmployeeLogic class is the business logic class that the ObjectDataSource uses.

  • The NorthwindEmployee class defines the data object that is returned by the GetAllEmployees method of the EmployeeLogic class.

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 .aspx page example that is provided. For information about how to install the Northwind Traders database, see How to: Install Sample Databases.

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

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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