ObjectDataSource Strongly Typed Source Object Example

Illustrates a custom middle-tier business object that can be used with an ObjectDataSource control.

Example

Description

The following code example illustrates a custom middle-tier business object that can be used with an ObjectDataSource control that specifies a strongly typed source object using the DataObjectTypeName property. This topic also illustrates an example ASP.NET page that uses the business object as the source for an ObjectDataSource control. The page includes a GridView control and a DetailsView control that are bound to the ObjectDataSource control.

To use the code, you can create a code file in your Web application's App_Code subdirectory and copy the code into the file. The business object will then be compiled dynamically and included as part of your Web application. Alternatively, you can compile the business object and place it in the Bin directory of an ASP.NET application or in the Global Assembly Cache (GAC). For more information on the App_Code and Bin directories, see Shared Code Folders in ASP.NET Web Sites.

Code

Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.ObjectDataSource

  PublicClass NorthwindEmployee  
    Private _employeeID AsIntegerPrivate _lastName AsStringPrivate _firstName AsStringPrivate _address AsStringPrivate _city AsStringPrivate _region AsStringPrivate _postalCode AsStringPublicSubNew()    
    EndSubPublicProperty EmployeeID AsIntegerGetReturn _employeeID
      EndGetSet
        _employeeID = value
      EndSetEndPropertyPublicProperty LastName AsStringGetReturn _lastName
      EndGetSet
        _lastName = value
      EndSetEndPropertyPublicProperty FirstName AsStringGetReturn _firstName
      EndGetSet
        _firstName = value
      EndSetEndPropertyPublicProperty Address AsStringGetReturn _address
      EndGetSet
        _address = value
      EndSetEndPropertyPublicProperty City AsStringGetReturn _city
      EndGetSet
        _city = value
      EndSetEndPropertyPublicProperty Region AsStringGetReturn _region
      EndGetSet
        _region = value
      EndSetEndPropertyPublicProperty PostalCode AsStringGetReturn _postalCode
      EndGetSet
        _postalCode = value
      EndSetEndPropertyEndClass
  '  '  Northwind Employee Data Factory  'PublicClass NorthwindEmployeeData  

    Private _connectionString AsStringPublicSubNew()    
      Initialize()
    EndSubPublicSub Initialize()    
      ' Initialize data source. Use "Northwind" connection string from configuration.If ConfigurationManager.ConnectionStrings("Northwind") IsNothingOrElse _
          ConfigurationManager.ConnectionStrings("Northwind").ConnectionString.Trim() = ""ThenThrowNew Exception("A connection string named 'Northwind' with a valid connection string " & _
                            "must exist in the <connectionStrings> configuration section for the application.")
      EndIf

      _connectionString = _
        ConfigurationManager.ConnectionStrings("Northwind").ConnectionString
    EndSub

    ' Select all employees.PublicFunction GetAllEmployees(sortColumns AsString, startRecord AsInteger, _
                                    maxRecords AsInteger) As List(of NorthwindEmployee)

      VerifySortColumns(sortColumns)

      Dim sqlCmd AsString = "SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode FROM Employees "If sortColumns.Trim() = ""Then
        sqlCmd &= "ORDER BY EmployeeID"Else
        sqlCmd &= "ORDER BY " & sortColumns
      EndIfDim conn As SqlConnection = New SqlConnection(_connectionString)
      Dim cmd  As SqlCommand    = New SqlCommand(sqlCmd, conn)

      Dim reader As SqlDataReader = NothingDim employees As List(of NorthwindEmployee) = New List(of NorthwindEmployee)()
      Dim count AsInteger = 0

      Try      
        conn.Open()

        reader = cmd.ExecuteReader()

        DoWhile reader.Read()        
          If count >= startRecord ThenIf employees.Count < maxRecords Then
              employees.Add(GetNorthwindEmployeeFromReader(reader))
            Else
              cmd.Cancel()
            EndIfEndIf         

          count += 1
        LoopCatch e As SqlException      
        ' Handle exception.FinallyIf reader IsNotNothingThen reader.Close() 
        conn.Close()
      EndTryReturn employees
    EndFunction

    '''''    ' Verify that only valid columns are specified in the sort expression to aSub a SQL Injection attack.PrivateSub VerifySortColumns(sortColumns AsString)    
      If sortColumns.ToLowerInvariant().EndsWith(" desc") Then _
        sortColumns = sortColumns.Substring(0, sortColumns.Length - 5)

      Dim columnNames() AsString = sortColumns.Split(",")

      ForEach columnName AsStringIn columnNames      
        SelectCase columnName.Trim().ToLowerInvariant()        
          Case"employeeid"Case"lastname"Case"firstname"Case""CaseElseThrowNew ArgumentException("SortColumns contains an invalid column name.")
        EndSelectNextEndSubPrivateFunction GetNorthwindEmployeeFromReader(reader As SqlDataReader) As NorthwindEmployee     
      Dim employee As NorthwindEmployee = New NorthwindEmployee()

      employee.EmployeeID = reader.GetInt32(0)
      employee.LastName   = reader.GetString(1)
      employee.FirstName  = reader.GetString(2)

      If reader.GetValue(3) IsNot DBNull.Value Then _
        employee.Address = reader.GetString(3)

      If reader.GetValue(4) IsNot DBNull.Value Then _
        employee.City = reader.GetString(4)

      If reader.GetValue(5) IsNot DBNull.Value Then _
        employee.Region = reader.GetString(5)

      If reader.GetValue(6) IsNot DBNull.Value Then _
        employee.PostalCode = reader.GetString(6)

      Return employee
    EndFunction


    ' Select an employee.PublicFunction GetEmployee(EmployeeID AsInteger) As List(of NorthwindEmployee)    
      Dim conn As SqlConnection = New SqlConnection(_connectionString)
      Dim cmd  As SqlCommand    = _
        New SqlCommand("SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode " & _
                       "  FROM Employees WHERE EmployeeID = @EmployeeID", conn) 
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID

      Dim reader As SqlDataReader = NothingDim employees As List(of NorthwindEmployee) = New List(of NorthwindEmployee)()

      Try      
        conn.Open()

        reader = cmd.ExecuteReader(CommandBehavior.SingleRow)

        DoWhile reader.Read()
          employees.Add(GetNorthwindEmployeeFromReader(reader))
        LoopCatch e As SqlException      
        ' Handle exception.FinallyIf reader IsNotNothingThen reader.Close() 
        conn.Close()
      EndTryReturn employees
    EndFunction

    '    ' Update the Employee by ID.    '   This method assumes that ConflictDetection is Set to OverwriteValues.PublicFunction UpdateEmployee(employee As NorthwindEmployee) AsIntegerIfString.IsNullOrEmpty(employee.FirstName) Then _
        ThrowNew ArgumentException("FirstName cannot be null or an empty string.")
      IfString.IsNullOrEmpty(employee.LastName) Then _
        ThrowNew ArgumentException("LastName cannot be null or an empty string.")

      If employee.Address    IsNothingThen employee.Address    = String.Empty 
      If employee.City       IsNothingThen employee.City       = String.Empty 
      If employee.Region     IsNothingThen employee.Region     = String.Empty 
      If employee.PostalCode IsNothingThen employee.PostalCode = String.Empty 

      Dim conn As SqlConnection = New SqlConnection(_connectionString)
      Dim cmd  As SqlCommand    = New SqlCommand("UPDATE Employees " & _
                                          "  SET FirstName=@FirstName, LastName=@LastName, " & _
                                          "  Address=@Address, City=@City, Region=@Region, " & _
                                          "  PostalCode=@PostalCode " & _
                                          "  WHERE EmployeeID=@EmployeeID", conn)  

      cmd.Parameters.Add("@FirstName",  SqlDbType.VarChar, 10).Value = employee.FirstName
      cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = employee.LastName
      cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = employee.Address
      cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = employee.City
      cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = employee.Region
      cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = employee.PostalCode
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = employee.EmployeeID

      Dim result AsInteger = 0

      Try      
        conn.Open()

        result = cmd.ExecuteNonQuery()
      Catch e As SqlException      
        ' Handle exception.Finally      
        conn.Close()
      EndTryReturn result
    EndFunction

    ' Insert an Employee.PublicFunction InsertEmployee(employee As NorthwindEmployee) AsIntegerIfString.IsNullOrEmpty(employee.FirstName) Then _
        ThrowNew ArgumentException("FirstName cannot be null or an empty string.")
      IfString.IsNullOrEmpty(employee.LastName) Then _
        ThrowNew ArgumentException("LastName cannot be null or an empty string.")

      If employee.Address    IsNothingThen employee.Address    = String.Empty 
      If employee.City       IsNothingThen employee.City       = String.Empty 
      If employee.Region     IsNothingThen employee.Region     = String.Empty 
      If employee.PostalCode IsNothingThen employee.PostalCode = String.Empty 

      Dim conn As SqlConnection = New SqlConnection(_connectionString)
      Dim cmd  As SqlCommand    = New SqlCommand("INSERT INTO Employees " & _
                                          "  (FirstName, LastName, Address, City, Region, PostalCode) " & _
                                          "  Values(@FirstName, @LastName, @Address, @City, @Region, @PostalCode) " & _
                                          "SELECT @EmployeeID = SCOPE_IDENTITY()", conn)  

      cmd.Parameters.Add("@FirstName",  SqlDbType.VarChar, 10).Value = employee.FirstName
      cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = employee.LastName
      cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = employee.Address
      cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = employee.City
      cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = employee.Region
      cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = employee.PostalCode
      Dim p As SqlParameter = cmd.Parameters.Add("@EmployeeID", SqlDbType.Int)
      p.Direction = ParameterDirection.Output

      Dim newEmployeeID AsInteger= 0

      Try      
        conn.Open()

        cmd.ExecuteNonQuery()

        newEmployeeID = CInt(p.Value)
      Catch e As SqlException      
        ' Handle exception.Finally      
        conn.Close()
      EndTryReturn newEmployeeID
    EndFunction

    '    ' Delete the Employee by ID.    '   This method assumes that ConflictDetection is Set to OverwriteValues.PublicFunction DeleteEmployee(employee As NorthwindEmployee) AsIntegerDim sqlCmd AsString = "DELETE FROM Employees WHERE EmployeeID = @EmployeeID"Dim conn As SqlConnection = New SqlConnection(_connectionString)
      Dim cmd  As SqlCommand    = New SqlCommand(sqlCmd, conn)  
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = employee.EmployeeID

      Dim result AsInteger = 0

      Try      
        conn.Open()

        result = cmd.ExecuteNonQuery()
      Catch e As SqlException      
        ' Handle exception.Finally      
        conn.Close()
      EndTryReturn result
    EndFunctionEndClassEndNamespace
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Samples.AspNet.ObjectDataSource
{
  publicclass NorthwindEmployee
  {
    privateint _employeeID;
    privatestring _lastName;
    privatestring _firstName;
    privatestring _address;
    privatestring _city;
    privatestring _region;
    privatestring _postalCode;

    public NorthwindEmployee()
    {
    }

    publicint EmployeeID
    {
      get { return _employeeID; }
      set { _employeeID = value; }
    }

    publicstring LastName
    {
      get { return _lastName; }
      set { _lastName = value; }
    }

    publicstring FirstName
    {
      get { return _firstName; }
      set { _firstName = value; }
    }

    publicstring Address
    {
      get { return _address; }
      set { _address = value; }
    }

    publicstring City
    {
      get { return _city; }
      set { _city = value; }
    }

    publicstring Region
    {
      get { return _region; }
      set { _region = value; }
    }

    publicstring PostalCode
    {
      get { return _postalCode; }
      set { _postalCode = value; }
    }
  }

  ////  Northwind Employee Data Factory//publicclass NorthwindEmployeeData
  {

    privatestring _connectionString;


    public NorthwindEmployeeData()
    {
      Initialize();
    }


    publicvoid Initialize()
    {
      // Initialize data source. Use "Northwind" connection stringfrom configuration.

      if (ConfigurationManager.ConnectionStrings["Northwind"] == null ||
          ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString.Trim() == "")
      {
        thrownew Exception("A connection string named 'Northwind' with a valid connection string " + 
                            "must exist in the <connectionStrings> configuration section for the application.");
      }

      _connectionString = 
        ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
    }


    // Select all employees.public List<NorthwindEmployee> GetAllEmployees(string sortColumns, int startRecord, int maxRecords)
    {
      VerifySortColumns(sortColumns);

      string sqlCmd = "SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode FROM Employees ";

      if (sortColumns.Trim() == "")
        sqlCmd += "ORDER BY EmployeeID";
      else
        sqlCmd += "ORDER BY " + sortColumns;

      SqlConnection conn = new SqlConnection(_connectionString);
      SqlCommand    cmd  = new SqlCommand(sqlCmd, conn);

      SqlDataReader reader = null; 
      List<NorthwindEmployee> employees = new List<NorthwindEmployee>();
      int count = 0;

      try
      {
        conn.Open();

        reader = cmd.ExecuteReader();

        while (reader.Read())
        {
          if (count >= startRecord)
          {
            if (employees.Count < maxRecords)
              employees.Add(GetNorthwindEmployeeFromReader(reader));
            else
              cmd.Cancel();
          }          

          count++;
        }

      }
      catch (SqlException e)
      {
        // Handle exception.
      }
      finally
      {
        if (reader != null) { reader.Close(); }
        conn.Close();
      }

      return employees;
    }


    //////////// Verify that only valid columns are specified in the sort expression to avoid a SQL Injection attack.privatevoid VerifySortColumns(string sortColumns)
    {
      if (sortColumns.ToLowerInvariant().EndsWith(" desc"))
        sortColumns = sortColumns.Substring(0, sortColumns.Length - 5);

      string[] columnNames = sortColumns.Split(',');

      foreach (string columnName in columnNames)
      {
        switch (columnName.Trim().ToLowerInvariant())
        {
          case"employeeid":
            break;
          case"lastname":
            break;
          case"firstname":
            break;
          case"":
            break;
          default:
            thrownew ArgumentException("SortColumns contains an invalid column name.");
            break;
        }
      }
    }


    private NorthwindEmployee GetNorthwindEmployeeFromReader(SqlDataReader reader)
    {
      NorthwindEmployee employee = new NorthwindEmployee();

      employee.EmployeeID = reader.GetInt32(0);
      employee.LastName   = reader.GetString(1);
      employee.FirstName  = reader.GetString(2);

      if (reader.GetValue(3) != DBNull.Value)
        employee.Address = reader.GetString(3);

      if (reader.GetValue(4) != DBNull.Value)
        employee.City = reader.GetString(4);

      if (reader.GetValue(5) != DBNull.Value)
        employee.Region = reader.GetString(5);

      if (reader.GetValue(6) != DBNull.Value)
        employee.PostalCode = reader.GetString(6);

      return employee;
    }



    // Select an employee.public List<NorthwindEmployee> GetEmployee(int EmployeeID)
    {
      SqlConnection conn = new SqlConnection(_connectionString);
      SqlCommand    cmd  = 
        new SqlCommand("SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode " +
                       "  FROM Employees WHERE EmployeeID = @EmployeeID", conn); 
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID;

      SqlDataReader reader = null;
      List<NorthwindEmployee> employees = new List<NorthwindEmployee>();

      try
      {
        conn.Open();

        reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

        while (reader.Read())
          employees.Add(GetNorthwindEmployeeFromReader(reader));
      }
      catch (SqlException e)
      {
        // Handle exception.
      }
      finally
      {
        if (reader != null) { reader.Close(); }

        conn.Close();
      }

      return employees;
    }


    //// Update the Employee by ID.//   This method assumes that ConflictDetection is set to OverwriteValues.publicint UpdateEmployee(NorthwindEmployee employee)
    {
      if (String.IsNullOrEmpty(employee.FirstName))
        thrownew ArgumentException("FirstName cannot be null or an empty string.");
      if (String.IsNullOrEmpty(employee.LastName))
        thrownew ArgumentException("LastName cannot be null or an empty string.");

      if (employee.Address    == null) { employee.Address    = String.Empty; }
      if (employee.City       == null) { employee.City       = String.Empty; }
      if (employee.Region     == null) { employee.Region     = String.Empty; }
      if (employee.PostalCode == null) { employee.PostalCode = String.Empty; }

      SqlConnection conn = new SqlConnection(_connectionString);
      SqlCommand    cmd  = new SqlCommand("UPDATE Employees " + 
                                          "  SET FirstName=@FirstName, LastName=@LastName, " + 
                                          "  Address=@Address, City=@City, Region=@Region, " +
                                          "  PostalCode=@PostalCode " +
                                          "  WHERE EmployeeID=@EmployeeID", conn);  

      cmd.Parameters.Add("@FirstName",  SqlDbType.VarChar, 10).Value = employee.FirstName;
      cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = employee.LastName;
      cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = employee.Address;
      cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = employee.City;
      cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = employee.Region;
      cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = employee.PostalCode;
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = employee.EmployeeID;

      int result = 0;

      try
      {
        conn.Open();

        result = cmd.ExecuteNonQuery();
      }
      catch (SqlException e)
      {
        // Handle exception.
      }
      finally
      {
        conn.Close();
      }

      return result;
    }


    // Insert an Employee.publicint InsertEmployee(NorthwindEmployee employee)
    {
      if (String.IsNullOrEmpty(employee.FirstName))
        thrownew ArgumentException("FirstName cannot be null or an empty string.");
      if (String.IsNullOrEmpty(employee.LastName))
        thrownew ArgumentException("LastName cannot be null or an empty string.");

      if (employee.Address    == null) { employee.Address    = String.Empty; }
      if (employee.City       == null) { employee.City       = String.Empty; }
      if (employee.Region     == null) { employee.Region     = String.Empty; }
      if (employee.PostalCode == null) { employee.PostalCode = String.Empty; }

      SqlConnection conn = new SqlConnection(_connectionString);
      SqlCommand    cmd  = new SqlCommand("INSERT INTO Employees " + 
                                          "  (FirstName, LastName, Address, City, Region, PostalCode) " +
                                          "  Values(@FirstName, @LastName, @Address, @City, @Region, @PostalCode); " +
                                          "SELECT @EmployeeID = SCOPE_IDENTITY()", conn);  

      cmd.Parameters.Add("@FirstName",  SqlDbType.VarChar, 10).Value = employee.FirstName;
      cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = employee.LastName;
      cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = employee.Address;
      cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = employee.City;
      cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = employee.Region;
      cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = employee.PostalCode;
      SqlParameter p = cmd.Parameters.Add("@EmployeeID", SqlDbType.Int);
      p.Direction = ParameterDirection.Output;

      int newEmployeeID = 0;

      try
      {
        conn.Open();

        cmd.ExecuteNonQuery();

        newEmployeeID = (int)p.Value;
      }
      catch (SqlException e)
      {
        // Handle exception.
      }
      finally
      {
        conn.Close();
      }

      return newEmployeeID;
    }


    //// Delete the Employee by ID.//   This method assumes that ConflictDetection is set to OverwriteValues.publicint DeleteEmployee(NorthwindEmployee employee)
    {
      string sqlCmd = "DELETE FROM Employees WHERE EmployeeID = @EmployeeID";

      SqlConnection conn = new SqlConnection(_connectionString);
      SqlCommand cmd = new SqlCommand(sqlCmd, conn);  
      cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = employee.EmployeeID;

      int result = 0;

      try
      {
        conn.Open();

        result = cmd.ExecuteNonQuery();
      }
      catch (SqlException e)
      {
        // Handle exception.
      }
      finally
      {
        conn.Close();
      }

      return result;
    }

  }
}
<%@ Page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Sub EmployeesDetailsView_ItemInserted(sender AsObject, e As DetailsViewInsertedEventArgs)  
    EmployeesGridView.DataBind()  
  EndSubSub EmployeesDetailsView_ItemUpdated(sender AsObject, e As DetailsViewUpdatedEventArgs)  
    EmployeesGridView.DataBind()
  EndSubSub EmployeesDetailsView_ItemDeleted(sender AsObject, e As DetailsViewDeletedEventArgs)  
    EmployeesGridView.DataBind()
  EndSubSub EmployeesGridView_OnSelectedIndexChanged(sender AsObject, e As EventArgs)  
    EmployeeDetailsObjectDataSource.SelectParameters("EmployeeID").DefaultValue = _
      EmployeesGridView.SelectedDataKey.Value.ToString()
    EmployeesDetailsView.DataBind()
  EndSubSub EmployeeDetailsObjectDataSource_OnInserted(sender AsObject, e As ObjectDataSourceStatusEventArgs)  
    EmployeeDetailsObjectDataSource.SelectParameters("EmployeeID").DefaultValue = _
      e.ReturnValue.ToString()
    EmployeesDetailsView.DataBind()
  EndSubSub EmployeeDetailsObjectDataSource_OnUpdated(sender AsObject, e As ObjectDataSourceStatusEventArgs)  
    IfCInt(e.ReturnValue) = 0 Then _
      Msg.Text = "Employee was not updated. Please try again."EndSubSub EmployeeDetailsObjectDataSource_OnDeleted(sender AsObject, e As ObjectDataSourceStatusEventArgs)  
    IfCInt(e.ReturnValue) = 0 Then _
      Msg.Text = "Employee was not deleted. Please try again."EndSubSub Page_Load()  
    Msg.Text = ""EndSub

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ObjectDataSource Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>ObjectDataSource Example</h3>
      <asp:Label id="Msg" runat="server" ForeColor="Red" />

      <asp:ObjectDataSource 
        ID="EmployeesObjectDataSource" 
        runat="server" 
        TypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployeeData" 
        DataObjectTypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployee"
        SortParameterName="SortColumns"
        EnablePaging="true"
        StartRowIndexParameterName="StartRecord"
        MaximumRowsParameterName="MaxRecords" 
        SelectMethod="GetAllEmployees" >
      </asp:ObjectDataSource>


      <asp:ObjectDataSource 
        ID="EmployeeDetailsObjectDataSource" 
        runat="server" 
        TypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployeeData" 
        DataObjectTypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployee"
        SelectMethod="GetEmployee"
        InsertMethod="InsertEmployee"
        UpdateMethod="UpdateEmployee"
        DeleteMethod="DeleteEmployee"
        OnInserted="EmployeeDetailsObjectDataSource_OnInserted"
        OnUpdated="EmployeeDetailsObjectDataSource_OnUpdated"
        OnDeleted="EmployeeDetailsObjectDataSource_OnDeleted">
        <SelectParameters>
          <asp:Parameter Name="EmployeeID" Type="Int32" />  
        </SelectParameters>
      </asp:ObjectDataSource>


      <table cellspacing="10">
        <tr>
          <td valign="top">
            <asp:GridView ID="EmployeesGridView" 
              DataSourceID="EmployeesObjectDataSource" 
              AutoGenerateColumns="false"
              AllowSorting="true"
              AllowPaging="true"
              PageSize="5"
              DataKeyNames="EmployeeID" 
              OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
              RunAt="server">

              <HeaderStyle backcolor="lightblue" forecolor="black"/>

              <Columns>                
                <asp:ButtonField Text="Details..."
                                 HeaderText="Show Details"
                                 CommandName="Select"/>  

                <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" SortExpression="EmployeeID" />
                <asp:BoundField DataField="FirstName"  HeaderText="First Name" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName"   HeaderText="Last Name" SortExpression="LastName, FirstName" />                    
              </Columns>                
            </asp:GridView>            
          </td>
          <td valign="top">                
            <asp:DetailsView ID="EmployeesDetailsView"
              DataSourceID="EmployeeDetailsObjectDataSource"
              AutoGenerateRows="false"
              EmptyDataText="No records."      
              DataKeyNames="EmployeeID"     
              Gridlines="Both" 
              AutoGenerateInsertButton="true"
              AutoGenerateEditButton="true"
              AutoGenerateDeleteButton="true"
              OnItemInserted="EmployeesDetailsView_ItemInserted"
              OnItemUpdated="EmployeesDetailsView_ItemUpdated"
              OnItemDeleted="EmployeesDetailsView_ItemDeleted" 
              RunAt="server">

              <HeaderStyle backcolor="Navy" forecolor="White"/>

              <RowStyle backcolor="White"/>

              <AlternatingRowStyle backcolor="LightGray"/>

              <EditRowStyle backcolor="LightCyan"/>

              <Fields>                  
                <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" InsertVisible="False"ReadOnly="true"/>                    
                <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>
                <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                    
                <asp:BoundField DataField="Address"    HeaderText="Address"/>                    
                <asp:BoundField DataField="City"       HeaderText="City"/>                        
                <asp:BoundField DataField="Region"     HeaderText="Region"/>
                <asp:BoundField DataField="PostalCode" HeaderText="Postal Code"/>                    
              </Fields>                    
            </asp:DetailsView>
          </td>                
        </tr>            
      </table>
    </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">
<script runat="server">

  void EmployeesDetailsView_ItemInserted(Object sender, DetailsViewInsertedEventArgs e)
  {
    EmployeesGridView.DataBind();  
  }


  void EmployeesDetailsView_ItemUpdated(Object sender, DetailsViewUpdatedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }


  void EmployeesDetailsView_ItemDeleted(Object sender, DetailsViewDeletedEventArgs e)
  {
    EmployeesGridView.DataBind();
  }

  void EmployeesGridView_OnSelectedIndexChanged(object sender, EventArgs e)
  {
    EmployeeDetailsObjectDataSource.SelectParameters["EmployeeID"].DefaultValue = 
      EmployeesGridView.SelectedDataKey.Value.ToString();
    EmployeesDetailsView.DataBind();
  }

  void EmployeeDetailsObjectDataSource_OnInserted(object sender, ObjectDataSourceStatusEventArgs e)
  {
    EmployeeDetailsObjectDataSource.SelectParameters["EmployeeID"].DefaultValue = 
      e.ReturnValue.ToString();
    EmployeesDetailsView.DataBind();
  }

  void EmployeeDetailsObjectDataSource_OnUpdated(object sender, ObjectDataSourceStatusEventArgs e)
  {
    if ((int)e.ReturnValue == 0)
      Msg.Text = "Employee was not updated. Please try again.";
  }

  void EmployeeDetailsObjectDataSource_OnDeleted(object sender, ObjectDataSourceStatusEventArgs e)
  {
    if ((int)e.ReturnValue == 0)
      Msg.Text = "Employee was not deleted. Please try again.";
  }

  void Page_Load()
  {
    Msg.Text = "";
  }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ObjectDataSource Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>ObjectDataSource Example</h3>
      <asp:Label id="Msg" runat="server" ForeColor="Red" />

      <asp:ObjectDataSource 
        ID="EmployeesObjectDataSource" 
        runat="server" 
        TypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployeeData" 
        DataObjectTypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployee"
        SortParameterName="SortColumns"
        EnablePaging="true"
        StartRowIndexParameterName="StartRecord"
        MaximumRowsParameterName="MaxRecords" 
        SelectMethod="GetAllEmployees" >
      </asp:ObjectDataSource>


      <asp:ObjectDataSource 
        ID="EmployeeDetailsObjectDataSource" 
        runat="server" 
        TypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployeeData" 
        DataObjectTypeName="Samples.AspNet.ObjectDataSource.NorthwindEmployee"
        SelectMethod="GetEmployee"
        InsertMethod="InsertEmployee"
        UpdateMethod="UpdateEmployee"
        DeleteMethod="DeleteEmployee"
        OnInserted="EmployeeDetailsObjectDataSource_OnInserted"
        OnUpdated="EmployeeDetailsObjectDataSource_OnUpdated"
        OnDeleted="EmployeeDetailsObjectDataSource_OnDeleted">
        <SelectParameters>
          <asp:Parameter Name="EmployeeID" Type="Int32" />  
        </SelectParameters>
      </asp:ObjectDataSource>


      <table cellspacing="10">
        <tr>
          <td valign="top">
            <asp:GridView ID="EmployeesGridView" 
              DataSourceID="EmployeesObjectDataSource" 
              AutoGenerateColumns="false"
              AllowSorting="true"
              AllowPaging="true"
              PageSize="5"
              DataKeyNames="EmployeeID" 
              OnSelectedIndexChanged="EmployeesGridView_OnSelectedIndexChanged"
              RunAt="server">

              <HeaderStyle backcolor="lightblue" forecolor="black"/>

              <Columns>                
                <asp:ButtonField Text="Details..."
                                 HeaderText="Show Details"
                                 CommandName="Select"/>  

                <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" SortExpression="EmployeeID" />
                <asp:BoundField DataField="FirstName"  HeaderText="First Name" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName"   HeaderText="Last Name" SortExpression="LastName, FirstName" />                    
              </Columns>                
            </asp:GridView>            
          </td>
          <td valign="top">                
            <asp:DetailsView ID="EmployeesDetailsView"
              DataSourceID="EmployeeDetailsObjectDataSource"
              AutoGenerateRows="false"
              EmptyDataText="No records."      
              DataKeyNames="EmployeeID"     
              Gridlines="Both" 
              AutoGenerateInsertButton="true"
              AutoGenerateEditButton="true"
              AutoGenerateDeleteButton="true"
              OnItemInserted="EmployeesDetailsView_ItemInserted"
              OnItemUpdated="EmployeesDetailsView_ItemUpdated"
              OnItemDeleted="EmployeesDetailsView_ItemDeleted" 
              RunAt="server">

              <HeaderStyle backcolor="Navy" forecolor="White"/>

              <RowStyle backcolor="White"/>

              <AlternatingRowStyle backcolor="LightGray"/>

              <EditRowStyle backcolor="LightCyan"/>

              <Fields>                  
                <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" InsertVisible="False" ReadOnly="true"/>                    
                <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>
                <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                    
                <asp:BoundField DataField="Address"    HeaderText="Address"/>                    
                <asp:BoundField DataField="City"       HeaderText="City"/>                        
                <asp:BoundField DataField="Region"     HeaderText="Region"/>
                <asp:BoundField DataField="PostalCode" HeaderText="Postal Code"/>                    
              </Fields>                    
            </asp:DetailsView>
          </td>                
        </tr>            
      </table>
    </form>
  </body>
</html>

Comments

The example requires a connection string for the sample Northwind database on a SQL Server. The connection string must be defined in the <connectionStrings> element of the application's configuration file. The connectionStrings section might look like the following example:

<configuration>
  <system.web>
    <connectionStrings>
      <add 
        name="Northwind" 
        connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;" />
    </connectionStrings>

  </system.web>
</configuration>

See Also

Reference

ObjectDataSource

ObjectDataSource Web Server Control Overview