共用方式為


使用參數和 ObjectDataSource 控制項

更新:2007 年 11 月

ObjectDataSource 控制項會根據 SelectMethodInsertMethodUpdateMethodDeleteMethod 屬性中識別的方法名稱,以及組成商務物件方法簽章的參數名稱,呼叫商務物件方法。當您在商務物件中建立方法時,必須確認商務物件方法接受的參數名稱和型別,符合 ObjectDataSource 控制項傳遞的參數名稱和類型 (參數順序並不重要)。

使用參數

ObjectDataSource 控制項就像所有的資料來源控制項,可以在執行階段接受輸入參數,並且在參數集合中加以管理。每個資料作業都有相關的參數集合。您可以在選取作業時使用 SelectParameters 集合,在更新作業時使用 UpdateParameters 集合等等。

您可以為每個參數指定名稱、型別、方向和預設值。從特定物件 (例如控制項、工作階段變數或使用者設定檔) 取得值的參數需要設定其他屬性。例如,ControlParameter 物件設定 ControlID 屬性以識別取得參數值的控制項,並且設定 PropertyName 屬性以識別包含參數值的屬性。如需詳細資訊,請參閱使用含有資料來源控制項的參數

下列程式碼範例示範 ObjectDataSource 控制項能夠呼叫的選取方法。方法會從資料來源取得參數並選取單一資料錄。

<DataObjectMethod(DataObjectMethodType.Select)> _
Public Shared Function GetEmployee(EmployeeID As Integer) As DataTable

  If Not _initialized Then Initialize()

  Dim conn As SqlConnection  = New SqlConnection(_connectionString)
  Dim da  As SqlDataAdapter  = _
    New SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode FROM Employees WHERE EmployeeID = @EmployeeID", conn) 
  da.SelectCommand.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID

  Dim ds As DataSet =  New DataSet() 

  Try      
    conn.Open()
    da.Fill(ds, "Employees")
  Catch e As SqlException
    ' Handle exception.
  Finally
    conn.Close()
  End Try

  If ds.Tables("Employees") IsNot Nothing Then _
    Return ds.Tables("Employees")

  Return Nothing
End Function
[DataObjectMethod(DataObjectMethodType.Select)]
public static DataTable GetEmployee(int EmployeeID)
{
  if (!_initialized) { Initialize(); }

  SqlConnection conn = new SqlConnection(_connectionString);
  SqlDataAdapter da  = 
    new SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode FROM Employees WHERE EmployeeID = @EmployeeID", conn); 
  da.SelectCommand.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID;

  DataSet ds =  new DataSet(); 

  try
  {
    conn.Open();
    da.Fill(ds, "Employees");
  }
  catch (SqlException e)
  {
    // Handle exception.
  }
  finally
  {
    conn.Close();
  }

  if (ds.Tables["Employees"] != null)
    return ds.Tables["Employees"];

  return null;
}

將參數傳遞至插入、更新和刪除方法

ObjectDataSource 控制項會各自根據 InsertParametersUpdateParametersDeleteParameters 集合,判斷插入、更新或刪除作業要呼叫的方法。此外,ObjectDataSource 控制項也會根據支援自動更新、插入和刪除作業的資料繫結控制項 (例如 GridViewFormView 控制項) 所傳遞的值自動建立參數。如需詳細資訊,請參閱資料來源控制項如何建立資料繫結欄位的參數

下列程式碼範例示範 ObjectDataSource 控制項能夠呼叫的方法。該方法會更新 Northwind 範例資料庫中的員工資訊。

<DataObjectMethod(DataObjectMethodType.Update)> _
Public Shared Function UpdateEmployee(EmployeeID As Integer, _
                                      FirstName As String, _
                                      LastName As String, _
                                      Address As String, _
                                      City As String, _
                                      Region As String, _
                                      PostalCode As String) As Boolean

  If String.IsNullOrEmpty(FirstName) Then _
    Throw New ArgumentException("FirstName cannot be null or an empty string.")
  If String.IsNullOrEmpty(LastName) Then _
    Throw New ArgumentException("LastName cannot be null or an empty string.")

  If Address    Is Nothing Then Address    = String.Empty 
  If City       Is Nothing Then City       = String.Empty 
  If Region     Is Nothing Then Region     = String.Empty 
  If PostalCode Is Nothing Then PostalCode = String.Empty 

  If Not _initialized Then Initialize()

  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 = FirstName
  cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = LastName
  cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = Address
  cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = City
  cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = Region
  cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = PostalCode
  cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID

  Try      
    conn.Open()

    If cmd.ExecuteNonQuery() <> 0 Then _
      Return False
  Catch e As SqlException
    ' Handle exception.
  Finally
    conn.Close()
  End Try

  Return True
End Function
[DataObjectMethod(DataObjectMethodType.Update)]
public static bool UpdateEmployee(int EmployeeID, string FirstName, string LastName, 
                                  string Address, string City, string Region, string PostalCode)
{
  if (String.IsNullOrEmpty(FirstName))
    throw new ArgumentException("FirstName cannot be null or an empty string.");
  if (String.IsNullOrEmpty(LastName))
    throw new ArgumentException("LastName cannot be null or an empty string.");

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

  if (!_initialized) { Initialize(); }

  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 = FirstName;
  cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = LastName;
  cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = Address;
  cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = City;
  cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = Region;
  cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = PostalCode;
  cmd.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = EmployeeID;

  try
  {
    conn.Open();

    if (cmd.ExecuteNonQuery() == 0)
      return false;
  }
  catch (SqlException e)
  {
    // Handle exception.
  }
  finally
  {
    conn.Close();
  }

  return true;
}

程式碼範例假設 ObjectDataSource 控制項的 ConflictDetection 屬性已經設定為 OverwriteChanges。如果 ConflictDetection 屬性設定為 CompareAllValues,商務物件方法就必須接受資料欄位原始值的參數。您可以使用 OldValuesParameterFormatString 屬性區分目前值與原始值的參數。您可以將 OldValuesParameterFormatString 屬性設定為用來格式化原始實值參數名稱的字串運算式,其中 {0} 字元代表欄位名稱。例如,如果將 OldValuesParameterFormatString 屬性設定為 original_{0},FirstName 欄位目前的值就會在名為 FirstName 的參數中傳遞,並且欄位原始值會在名為 original_FirstName 的參數中傳遞。

識別排序和分頁的參數

除了指定 Select 商務物件方法的 SelectParameters 物件外,您也可以包含排序和分頁的參數。這能夠讓您排序資料來源物件中的資料,以及限制資料來源物件只能夠將結果傳回資料的要求網頁。

識別排序參數

您可以使用 ObjectDataSource 控制項的 SortParameterName 屬性,指定 Select 商務物件方法的排序參數。SortParameterName 屬性會識別用來將排序資料行名稱,傳遞給商務物件方法的參數名稱。參數型別是字串。

GridView 之類的某些資料繫結控制項能夠自動將排序參數傳遞至 ObjectDataSource 控制項。當支援排序的資料繫結控制項繫結至 ObjectDataSource 控制項時,資料繫結控制項會傳遞排序運算式,以識別用來排序結果的資料行。例如,GridView 控制項會在 SortExpression 屬性中傳遞排序值。ObjectDataSource 控制項會根據傳遞給它的排序運算式,設定 SortParameterName 屬性識別的參數值。排序運算式能夠指定一個以上的資料行。如果的確指定了多個資料行,資料行名稱會以逗號分隔。若要指定遞減排序,排序運算式會包含之後跟隨 DESC 修飾詞 (Modifier) 的排序資料行名稱。例如,將 LastName 和 FirstName 資料行識別為用來排序資料行的排序運算式,在遞增排序時會是 "LastName, FirstName",而在遞減排序時會是 "LastName, FirstName DESC"。

識別分頁參數

您可以指定 Select 方法的其他參數,以識別要傳回的資料網頁。ObjectDataSource 控制項支援識別分頁參數的兩種屬性:

  • StartRowIndexParameterName 屬性會在用來指定資料網頁開頭資料列的商務物件選取方法中,識別參數名稱。

  • MaximumRowsParameterName 屬性會在用來指定資料網頁資料列數目的商務物件選取方法中,識別參數名稱。

StartRowIndexParameterNameMaximumRowsParameterName 屬性識別的兩種參數都是 Int32 型別。

下列程式碼範例示範 ObjectDataSource 控制項,這個控制項是設定為將排序和分頁參數傳遞至指定商務物件的 Select 方法 :

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

下列程式碼範例示範在前一個範例中呼叫的 Select 商務物件方法。商務物件方法會從 Northwind 範例資料庫傳回資料網頁,並且以指定的順序排序。

Public Shared Sub Initialize()    
  ' Initialize data source. Use "Northwind" connection string from configuration.

  If ConfigurationManager.ConnectionStrings("Northwind") Is Nothing OrElse _
     ConfigurationManager.ConnectionStrings("Northwind").ConnectionString.Trim() = "" Then      
    Throw New Exception("A connection string named 'Northwind' with a valid connection string " & _
                        "must exist in the <connectionStrings> configuration section for the application.")
  End If

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

  _initialized = True
End Sub



' Select all employees.

<DataObjectMethod(DataObjectMethodType.Select, True)> _
Public Shared Function GetAllEmployees(sortColumns As String, startRecord As Integer, maxRecords As Integer) As DataTable

  VerifySortColumns(sortColumns)

  If Not _initialized Then Initialize()

  Dim sqlCommand As String = "SELECT EmployeeID, LastName, FirstName, Address, City, Region, PostalCode FROM Employees "

  If sortColumns.Trim() = "" Then
    sqlCommand &= "ORDER BY EmployeeID"
  Else
    sqlCommand &= "ORDER BY " & sortColumns
  End If

  Dim conn As SqlConnection  = New SqlConnection(_connectionString)
  Dim da   As SqlDataAdapter = New SqlDataAdapter(sqlCommand, conn) 

  Dim ds As DataSet =  New DataSet() 

  Try
    conn.Open()
    da.Fill(ds, startRecord, maxRecords, "Employees")
  Catch e As SqlException
    ' Handle exception.
  Finally      
    conn.Close()
  End Try

  If ds.Tables("Employees") IsNot Nothing Then _
    Return ds.Tables("Employees")

  Return Nothing
End Function


'''''
' Verify that only valid columns are specified in the sort expression to aSub a SQL Injection attack.

Private Shared Sub VerifySortColumns(sortColumns As String)

  If sortColumns.ToLowerInvariant().EndsWith(" desc") Then _
    sortColumns = sortColumns.Substring(0, sortColumns.Length - 5)

  Dim columnNames() As String = sortColumns.Split(",")

  For Each columnName As String In columnNames      
    Select Case columnName.Trim().ToLowerInvariant()        
      Case "employeeid"
      Case "lastname"
      Case "firstname"
      Case ""
      Case Else
        Throw New ArgumentException("SortColumns contains an invalid column name.")
    End Select
  Next
End Sub
public static void Initialize()
{
  // Initialize data source. Use "Northwind" connection string from configuration.

  if (ConfigurationManager.ConnectionStrings["Northwind"] == null ||
      ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString.Trim() == "")
  {
    throw new 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;

  _initialized = true;
}


// Select all employees.

[DataObjectMethod(DataObjectMethodType.Select, true)]
public static DataTable GetAllEmployees(string sortColumns, int startRecord, int maxRecords)
{
  VerifySortColumns(sortColumns);

  if (!_initialized) { Initialize(); }

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

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

  SqlConnection conn = new SqlConnection(_connectionString);
  SqlDataAdapter da  = new SqlDataAdapter(sqlCommand, conn); 

  DataSet ds =  new DataSet(); 

  try
  {
    conn.Open();
    da.Fill(ds, startRecord, maxRecords, "Employees");
  }
  catch (SqlException e)
  {
    // Handle exception.
  }
  finally
  {
    conn.Close();
  }

  if (ds.Tables["Employees"] != null)
    return ds.Tables["Employees"];

  return null;
}


//////////
// Verify that only valid columns are specified in the sort expression to avoid a SQL Injection attack.

private static void 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:
        throw new ArgumentException("SortColumns contains an invalid column name.");
        break;
    }
  }
}

參數方向

根據預設,商務物件方法的所有參數都是輸入參數。如果商務物件方法包含將值傳回 ObjectDataSource 控制項的輸出參數,您必須按照使用含有資料來源控制項的參數中的說明,使用參數方向明確指定參數。

下列程式碼範例會顯示設定為接受型別 Int32 之輸出參數的 ObjectDataSource 控制項。此輸出參數會傳回從 InsertMethod 屬性所指定之方法自動產生的主索引鍵值。

<asp:ObjectDataSource 
  ID="EmployeeDetailsObjectDataSource" 
   
  TypeName="Samples.AspNet.Controls.NorthwindEmployee" 
  SelectMethod="GetEmployee" 
  UpdateMethod="UpdateEmployee"
  DeleteMethod="DeleteEmployee"
  InsertMethod="InsertEmployee" 
  OnInserted="EmployeeDetailsObjectDataSource_OnInserted" >
  <SelectParameters>
    <asp:Parameter Name="EmployeeID" />  
  </SelectParameters>
  <InsertParameters>
    <asp:Parameter Name="NewEmployeeID" Direction="Output" 
                   Type="Int32" DefaultValue="0" />
  </InsertParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource 
  ID="EmployeeDetailsObjectDataSource" 
   
  TypeName="Samples.AspNet.Controls.NorthwindEmployee" 
  SelectMethod="GetEmployee" 
  UpdateMethod="UpdateEmployee"
  DeleteMethod="DeleteEmployee"
  InsertMethod="InsertEmployee" 
  OnInserted="EmployeeDetailsObjectDataSource_OnInserted" >
  <SelectParameters>
    <asp:Parameter Name="EmployeeID" />  
  </SelectParameters>
  <InsertParameters>
    <asp:Parameter Name="NewEmployeeID" Direction="Output" 
                   Type="Int32" DefaultValue="0" />
  </InsertParameters>
</asp:ObjectDataSource>

下列程式碼範例示範 Insert 商務物件方法,這個方法會將主索引鍵值當做輸出參數傳回:

<DataObjectMethod(DataObjectMethodType.Insert)> _
Public Shared Function InsertEmployee(ByRef NewEmployeeID As Integer, _
                                      FirstName As String, _
                                      LastName As String, _
                                      Address As String, _
                                      City As String, _
                                      Region As String, _
                                      PostalCode As String) As Boolean

  If String.IsNullOrEmpty(FirstName) Then _
    Throw New ArgumentException("FirstName cannot be null or an empty string.")
  If String.IsNullOrEmpty(LastName) Then _
    Throw New ArgumentException("LastName cannot be null or an empty string.")

  If Address    Is Nothing Then Address    = String.Empty 
  If City       Is Nothing Then City       = String.Empty 
  If Region     Is Nothing Then Region     = String.Empty 
  If PostalCode Is Nothing Then PostalCode = String.Empty 

  If Not _initialized Then Initialize()

  NewEmployeeID = -1

  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 = FirstName
  cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = LastName
  cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = Address
  cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = City
  cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = Region
  cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = PostalCode
  Dim p As SqlParameter = cmd.Parameters.Add("@EmployeeID", SqlDbType.Int)
  p.Direction = ParameterDirection.Output

  Try
    conn.Open()

    cmd.ExecuteNonQuery()

    NewEmployeeID = CInt(p.Value)
  Catch e As SqlException
    ' Handle exception.
  Finally
    conn.Close()
  End Try

  Return True
End Function
[DataObjectMethod(DataObjectMethodType.Insert)]
public static bool InsertEmployee(out int NewEmployeeID, string FirstName, string LastName, 
                                  string Address, string City, string Region, string PostalCode)
{
  if (String.IsNullOrEmpty(FirstName))
    throw new ArgumentException("FirstName cannot be null or an empty string.");
  if (String.IsNullOrEmpty(LastName))
    throw new ArgumentException("LastName cannot be null or an empty string.");

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

  if (!_initialized) { Initialize(); }

  NewEmployeeID = -1;

  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 = FirstName;
  cmd.Parameters.Add("@LastName",   SqlDbType.VarChar, 20).Value = LastName;
  cmd.Parameters.Add("@Address",    SqlDbType.VarChar, 60).Value = Address;
  cmd.Parameters.Add("@City",       SqlDbType.VarChar, 15).Value = City;
  cmd.Parameters.Add("@Region",     SqlDbType.VarChar, 15).Value = Region;
  cmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10).Value = PostalCode;
  SqlParameter p = cmd.Parameters.Add("@EmployeeID", SqlDbType.Int);
  p.Direction = ParameterDirection.Output;

  try
  {
    conn.Open();

    cmd.ExecuteNonQuery();

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

  return true;
}

參數資料型別

根據預設,商務物件方法的所有參數都是 Object 型別。如果商務物件方法包含不同型別的參數,您必須明確指定強型別 (Strongly Typed) 參數。如需詳細資訊,請參閱使用含有資料來源控制項的參數

傳遞自訂參數型別

大部分的商務物件方法簽章會取得 StringInt32 型別的參數。然而,您使用的商務物件方法可能會使用一個或多個複雜型別或使用者定義型別的參數。若要使用複雜或使用者定義的參數型別,您可以使用 ObjectDataSource 控制項的 DataObjectTypeName 屬性。

在商務物件中若建立使用長參數清單的方法,將控制項的值以一對一的方式,對應至資料存放區的值,可能會產生無法輕易重複使用的程式碼。比較好的作法是將資料封裝在自訂類別 (Class) 中,然後將類別的執行個體 (Instance) 當做參數傳遞。如此一來,組成類別執行個體的資料 (例如員工記錄),就能夠不需要變更資料來源物件所公開 (Expose) 的公用介面,即可加以變更。下列程式碼範例示範名為 NorthwindExployee 的類別,這個類別會定義員工資料,並且能夠當做參數傳遞給商務物件。

public class NorthwindEmployee {
    public NorthwindEmployee() { }
    private int _empId;
    private string _firstName;
    public int EmpId {
      get { return _empId; }
      set { _empId = value; }
    }
    public string FirstName {
      get { return _firstName; }
      set { _firstName = value; }
    }
    // Additional code for the class.
}
Public Class NorthwindEmployee
    Public Sub New()
    End Sub

    Private _empId As String
    Public Property EmpId() As Integer
        Get
            Return _empId
        End Get
        Set
            _empId = value
        End Set
    End Property 

    Private _firstName As String
    Public Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set
            _firstName = value
        End Set
    End Property

    ' Additional code for the class.
End Class

若要接受之前類別的執行個體當做參數,就要使用下列簽章定義商務物件的 UpdateEmployeeInfo 方法:

public void UpdateEmployeeInfo(NorthwindEmployee emp) {
}
Public Sub UpdateEmployeeInfo(emp As NorthwindEmployee)
End Sub

雖然您無法將參數的 Type 設定為自訂類別名稱,但是能夠將 ObjectDataSource 控制項的 DataObjectTypeName 屬性設定為自訂使用者定義型別的名稱,例如 NorthwindEmployee 類別,然後將型別的執行個體傳遞給商務物件資料方法。若要將使用者定義物件傳遞給資料來源物件,就必須滿足下列條件:

  • 使用者定義型別必須有預設建構函式 (不使用參數的建構函式)。

  • 使用者定義型別必須定義公用屬性,其名稱必須符合從資料繫結控制項 (例如 GridViewDetailsView) 傳遞給資料來源控制項的字典項目。如需這些字典的詳細資訊,請參閱使用含有資料來源控制項的參數

  • 資料來源物件的公用屬性必須同時公開 get 和 set 存取子。

下列程式碼範例示範藉由呼叫名為 EmployeeLogic 商務物件的 UpdateEmployeeInfo 方法,執行更新作業的 ObjectDataSource 控制項。ObjectDataSource 控制項是設定為將 NorthwindEmployee 類別的執行個體傳遞給更新方法。

<asp:objectdatasource
  
  id="ObjectDataSource1"
  typename="EmployeeLogic"
  selectmethod="GetAllEmployees"
  updatemethod="UpdateEmployeeInfo"
  dataobjecttypename="NorthwindEmployee" />

在某些情況下,商務物件方法會有包含多種複雜參數型別的參數清單。在這種情況下,您可以使用 ObjectDataSource 控制項,但是必須以程式設計方式將參數加入至 ObjectDataSource 控制項。若要這樣做,請處理在執行資料作業之前引發的事件,例如 InsertingUpdatingDeleting 事件,然後在 ObjectDataSourceMethodEventArgs 類別公開的 InputParameters 集合中設定值。

請參閱

參考

ObjectDataSource Web 伺服器控制項概觀

ObjectDataSource

Parameter