Share via


HOW TO:將物件繫結到 Windows Form 控制項 (Entity Framework)

物件服務可以讓您將 Windows Form 控制項 (例如 ComboBoxDataGridView) 繫結到 EntityCollectionObjectQuery 結果。建議您不要將控制項直接繫結到 ObjectQuery,最好是將它們繫結到 Execute 方法的結果。如需詳細資訊,請參閱將物件與控制項繫結 (Entity Framework)

本主題的範例是根據 Adventure Works Sales Model。若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:以手動方式定義 Entity Data Model (Entity Framework) 中的程序。

範例

下列範例是來自 Windows Form。表單載入時,SalesOrderHeader 物件的 ObjectResult 會藉由呼叫 ObjectQueryExecute 方法傳回。這個結果會繫結到下拉式方塊。選取某個訂單時,SalesOrderDetail 物件的相關 EntityCollection 便會繫結到 DataGridView 控制項。

Imports System
Imports System.Collections.Generic
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports AdventureWorksModel

Public Class Main
    Public Sub New()
        ' Initializes the designer-generated controls.
        InitializeComponent()
    End Sub
    Private context As AdventureWorksEntities
    Private customerId As Integer = 277
    Private Sub Main_Load(ByVal sender As System.Object, _
                           ByVal e As System.EventArgs) _
                           Handles MyBase.Load
        ' Initialize the object context.
        context = New AdventureWorksEntities()
        Try
            ' Create a query for orders that includes line items.
            Dim orderQuery As ObjectQuery(Of SalesOrderHeader) = _
            context.SalesOrderHeader _
                    .Where("it.CustomerID = @customerId", _
                    New ObjectParameter("customerId", customerId)) _
            .Include("SalesOrderDetail")

            ' Bind the combo box to the ObjectResult of SalesOrderHeader 
            ' that is returned when the query is executed.
            Me.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly)

            ' Display the PO number in the combo box.
            Me.ordersListBox.DisplayMember = "PurchaseOrderNumber"

        Catch ex As EntitySqlException
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub ordersListBox_SelectedIndexChanged(ByVal sender As System.Object, _
                                                    ByVal e As System.EventArgs) _
                                                    Handles ordersListBox.SelectedIndexChanged
        ' Get the currently selected SalesOrderHeader object.
        Dim order As SalesOrderHeader = CType(Me.ordersListBox.SelectedItem,  _
        SalesOrderHeader)

        ' Bind the items for this order to the DataGridView.
        lineItemsDataGrid.DataSource = order.SalesOrderDetail
    End Sub

    Private Sub saveButton_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles saveButton.Click
        ' Get the current order. 
        Dim order As SalesOrderHeader = CType(ordersListBox.SelectedItem,  _
            SalesOrderHeader)

        Try
            ' Save changes in the object context.
            context.SaveChanges(True)

        Catch ex As OptimisticConcurrencyException
            ' Resolve the concurrently conflict by refreshing the 
            ' object context before saving changes. 
            context.Refresh(RefreshMode.ClientWins, order.SalesOrderDetail)

            ' Resave changes in the object context.
            context.SaveChanges(True)
        Catch ex As Exception
            MessageBox.Show(ex.InnerException.Message, "An error has occured")
        Finally
            ' Refresh the latest data from the database.
            context.Refresh(RefreshMode.StoreWins, order)
            Me.Refresh()
        End Try
    End Sub
End Class
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using AdventureWorksModel;

namespace Microsoft.Samples.Edm
{
    public partial class Main : Form
    {
        private AdventureWorksEntities context;
        private int customerId = 277;

        public Main()
        {
            // Initializes the designer-generated controls.
            InitializeComponent();
        }
        
        private void Main_Load(object sender, EventArgs e)
        {
            // Initialize the object context.
            context = new AdventureWorksEntities();
            try
            {
                // Create a query for orders that includes line items.
                ObjectQuery<SalesOrderHeader> orderQuery = context.SalesOrderHeader
                    .Where("it.CustomerID = @customerId", 
                    new ObjectParameter("customerId", customerId))
                    .Include("SalesOrderDetail");

                // Bind the combo box to the ObjectResult of SalesOrderHeader 
                // that is returned when the query is executed.
                this.ordersListBox.DataSource = orderQuery.Execute(MergeOption.AppendOnly);

                // Display the PO number in the combo box.
                this.ordersListBox.DisplayMember = "PurchaseOrderNumber";
            }
            catch (EntitySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ordersListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the currently selected SalesOrderHeader object.
            SalesOrderHeader order = (SalesOrderHeader)this.ordersListBox.SelectedItem;

            // Bind the items for this order to the DataGridView.
            lineItemsDataGrid.DataSource = order.SalesOrderDetail;
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            // Get the current order.    
            SalesOrderHeader order = (SalesOrderHeader)ordersListBox.SelectedItem;

            try
            {
                // Save changes in the object context.
                context.SaveChanges(true);
            }
            catch (OptimisticConcurrencyException)
            {
                // Resolve the concurrently conflict by refreshing the 
                // object context before saving changes. 
                context.Refresh(RefreshMode.ClientWins, order.SalesOrderDetail);

                // Resave changes in the object context.
                context.SaveChanges(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.Message, "An error has occured");
            }
            finally
            {
                //  Refresh the latest data from the database.
                context.Refresh(RefreshMode.StoreWins, order);
                this.Refresh();
            }
        }
    }
}

另請參閱

工作

HOW TO:將物件繫結到 Windows Presentation Foundation 控制項 (Entity Framework)
HOW TO:將物件加入做為專案資料來源 (Entity Framework)

概念

將物件與控制項繫結 (Entity Framework)
將實體資料繫結至控制項 (應用程式案例)