ObjectDataSource.Selected 事件

定義

發生於 Select() 作業已經完成時。Occurs when a Select() operation has completed.

public:
 event System::Web::UI::WebControls::ObjectDataSourceStatusEventHandler ^ Selected;
public event System.Web.UI.WebControls.ObjectDataSourceStatusEventHandler Selected;
member this.Selected : System.Web.UI.WebControls.ObjectDataSourceStatusEventHandler 
Public Custom Event Selected As ObjectDataSourceStatusEventHandler 

事件類型

ObjectDataSourceStatusEventHandler

範例

下列三個範例顯示網頁、程式碼後置頁面類別,以及可讓使用者在 Northwind 資料庫的 Employees 資料表中抓取和更新記錄的資料存取類別。The following three examples show a Web page, a code-behind page class, and a data-access class that enable a user to retrieve and update records in the Employees table in the Northwind database.

第一個範例會顯示一個網頁,其中包含兩個 ObjectDataSource 控制項、一個 DropDownList 控制項和一個 DetailsView 控制項。The first example shows a Web page that contains two ObjectDataSource controls, a DropDownList control, and a DetailsView control. 第一個 ObjectDataSource 控制項和 DropDownList 控制項是用來從資料庫中取出和顯示員工名稱。The first ObjectDataSource control and the DropDownList control are used to retrieve and display employee names from the database. 第二個 ObjectDataSource 控制項和 DetailsView 控制項用來抓取、顯示及修改使用者選取之員工記錄中的資料。The second ObjectDataSource control and the DetailsView control are used to retrieve, display, and modify the data from the employee record that is selected by the user.

<form id="Form1" method="post" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>
<form id="form1" runat="server">

    <asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />

    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>

    <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      UpdateMethod="UpdateEmployeeAddress"
      OnUpdating="EmployeeUpdating"
      OnSelected="EmployeeSelected"
      TypeName="Samples.AspNet.CS.EmployeeLogic" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false"
        AutoGenerateEditButton="true">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
   
</form>

第二個範例會顯示和事件的處理常式 Selected UpdatingThe second example shows handlers for the Selected and Updating events. Selected事件處理常式會序列化包含從 Employee 資料表取得之資料的物件。The Selected event handler serializes the object that contains data that was retrieved from the Employee table. 序列化的物件會以檢視狀態儲存。The serialized object is stored in view state. Updating事件處理常式會還原序列化 view 狀態中的物件,其中包含正在更新之資料記錄的原始資料。The Updating event handler deserializes the object in view state that contains the original data for the data record that is being updated. 包含原始資料的物件會當做參數傳遞給 Update 方法。The object that contains the original data is passed as a parameter to the Update method. 原始資料必須傳遞到資料庫,才能用來檢查其他進程是否已修改資料。The original data must be passed to the database so that it can be used to check whether the data has been modified by another process.

public void EmployeeUpdating(object source, ObjectDataSourceMethodEventArgs e)
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));

    String xmlData = ViewState["OriginalEmployee"].ToString();
    XmlReader reader = XmlReader.Create(new StringReader(xmlData));
    Employee originalEmployee = (Employee)dcs.ReadObject(reader);
    reader.Close();

    e.InputParameters.Add("originalEmployee", originalEmployee);
}

public void EmployeeSelected(object source, ObjectDataSourceStatusEventArgs e)
{
    if (e.ReturnValue != null)
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);
        dcs.WriteObject(writer, e.ReturnValue);
        writer.Close();

        ViewState["OriginalEmployee"] = sb.ToString();
    }
}
Public Sub EmployeeUpdating(ByVal source As Object, ByVal e As ObjectDataSourceMethodEventArgs)
    Dim dcs As New DataContractSerializer(GetType(Employee))
    Dim xmlData As String
    Dim reader As XmlReader
    Dim originalEmployee As Employee

    xmlData = ViewState("OriginalEmployee").ToString()
    reader = XmlReader.Create(New StringReader(xmlData))
    originalEmployee = CType(dcs.ReadObject(reader), Employee)
    reader.Close()

    e.InputParameters.Add("originalEmployee", originalEmployee)
End Sub

Public Sub EmployeeSelected(ByVal source As Object, ByVal e As ObjectDataSourceStatusEventArgs)
    If e.ReturnValue IsNot Nothing Then
        Dim dcs As New DataContractSerializer(GetType(Employee))
        Dim sb As New StringBuilder()
        Dim writer As XmlWriter
        writer = XmlWriter.Create(sb)
        dcs.WriteObject(writer, e.ReturnValue)
        writer.Close()

        ViewState("OriginalEmployee") = sb.ToString()
    End If
End Sub

第三個範例顯示與 Northwind 資料庫互動的資料存取類別。The third example shows the data access class that interacts with the Northwind database. 類別會使用 LINQ 來查詢及更新 Employees 資料表。The class uses LINQ to query and update the Employees table. 此範例需要一個代表 Northwind 資料庫和 Employees 資料表的 LINQ to SQL 類別。The example requires a LINQ to SQL class that represents the Northwind database and Employees table. 如需詳細資訊,請參閱 如何:在 Web 專案中建立 LINQ to SQL 類別For more information, see How to: Create LINQ to SQL Classes in a Web Project.

public class EmployeeLogic
{
    public static Array GetFullNamesAndIDs()
    {
        NorthwindDataContext ndc = new NorthwindDataContext();

        var employeeQuery =
            from e in ndc.Employees
            orderby e.LastName
            select new { FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID };

        return employeeQuery.ToArray();
    }

    public static Employee GetEmployee(int empID)
    {
        if (empID < 0)
        {
            return null;
        }
        else
        {
            NorthwindDataContext ndc = new NorthwindDataContext();
            var employeeQuery =
                from e in ndc.Employees
                where e.EmployeeID == empID
                select e;

            return employeeQuery.Single();
        }
    }
 
    public static void UpdateEmployeeAddress(Employee originalEmployee, string address, string city, string postalcode)
    {
        NorthwindDataContext ndc = new NorthwindDataContext();
        ndc.Employees.Attach(originalEmployee, false);
        originalEmployee.Address = address;
        originalEmployee.City = city;
        originalEmployee.PostalCode = postalcode;
        ndc.SubmitChanges();
    }
}
Public Class EmployeeLogic
    Public Shared Function GetFullNamesAndIDs() As Array
        Dim ndc As New NorthwindDataContext()

        Dim employeeQuery = _
            From e In ndc.Employees _
            Order By e.LastName _
            Select FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID

        Return employeeQuery.ToArray()
    End Function

    Public Shared Function GetEmployee(ByVal empID As Integer) As Employee

        If (empID < 0) Then
            Return Nothing
        Else
            Dim ndc As New NorthwindDataContext()
            Dim employeeQuery = _
                From e In ndc.Employees _
                Where e.EmployeeID = empID _
                Select e

            Return employeeQuery.Single()
        End If
    End Function

    Public Shared Sub UpdateEmployeeAddress(ByVal originalEmployee As Employee, ByVal address As String, ByVal city As String, ByVal postalcode As String)

        Dim ndc As New NorthwindDataContext()
        ndc.Employees.Attach(originalEmployee, False)
        originalEmployee.Address = address
        originalEmployee.City = city
        originalEmployee.PostalCode = postalcode
        ndc.SubmitChanges()
    End Sub
End Class

備註

處理 Selected 事件以檢查傳回值或輸出參數的值,或判斷作業完成後是否擲回例外狀況 SelectHandle the Selected event to examine the values of a return value or output parameters, or to determine whether an exception was thrown after a Select operation has completed. 傳回值、輸出參數和例外狀況處理屬性可從 ObjectDataSourceStatusEventArgs 與事件相關聯的物件中取得。The return value, output parameters, and exception handling properties are available from the ObjectDataSourceStatusEventArgs object that is associated with the event.

如需如何處理事件的詳細資訊,請參閱 處理和引發事件For more information about how to handle events, see Handling and Raising Events.

適用於

另請參閱