チュートリアル: オブジェクトのデータへの接続 (Windows フォーム)

このチュートリアルでは、顧客データおよび注文データを保持するオブジェクトと、各オブジェクトのオブジェクト データ ソースを作成します。 オブジェクト データ ソースは、[データ ソース] ウィンドウに表示されます。このウィンドウからフォームに項目をドラッグして、各オブジェクトのパブリック プロパティのデータにバインドするコントロールを作成します。 このチュートリアルでは、TableAdapter を使ってデータをデータベースからフェッチし、オブジェクトに設定する方法についても説明します。

データ ソース構成ウィザードを実行し、データ ソースの型として [オブジェクト] を選択すると、オブジェクト データ ソースが作成されます。 データ ソース構成ウィザードを完了すると、[データ ソース] ウィンドウでオブジェクトのパブリック プロパティをフォームにドラッグできるようになります。

このチュートリアルでは、以下のタスクを行います。

  • 新しい Windows フォーム アプリケーション プロジェクトを作成します。

  • 顧客および注文を表すカスタム オブジェクトを作成します。

  • データ ソース構成ウィザードを使用して、カスタム オブジェクトに基づくオブジェクト データ ソースを作成して構成します。

  • カスタム オブジェクトのデータにバインドされているフォームにコントロールを追加します。

  • オブジェクトとデータベースの間でデータを移動するためにデータセットと TableAdapter を作成します。

  • TableAdapter のメイン クエリを編集します。

  • クエリを TableAdapter に追加します。

  • オブジェクトにデータベースのデータを設定します。

プロジェクトの作成

新しい Windows フォーム アプリケーション プロジェクトを作成するには

  1. [ファイル] メニューの [新しいプロジェクト] をクリックします。

  2. [プロジェクトの種類] ペインで、使用する言語のノードの下にある [Windows] をクリックします。

  3. [テンプレート] ペインの [Windows フォーム アプリケーション] をクリックします。

  4. [名前] ボックスに「ObjectBindingWalkthrough」と入力し、[OK] をクリックします。

    ObjectBindingWalkthrough プロジェクトが作成されてソリューション エクスプローラーに追加されます。

このチュートリアルでは、バインド先のオブジェクトが必要です。 最初に、顧客および注文を表すサンプル オブジェクトを作成します。 顧客を表すには、1 人の顧客を表す Customer オブジェクトを作成します。 注文を表すには、1 件の注文を表す Order オブジェクトと、Order オブジェクトのコレクションを表す Orders オブジェクトを作成します。 Customer オブジェクトのコレクションには、BindingSource クラスに組み込まれているコレクションを使用します (詳しくはこのチュートリアルの後半で説明します)。

Customer オブジェクトの作成

Customer オブジェクトを作成するには

  1. [プロジェクト] メニューの [クラスの追加] を選択します。

  2. 新しいクラスに「Customer」という名前を付け、[追加] をクリックします。

  3. Customer クラスのコードを次のコードで置き換えます。

    注意

    Customer オブジェクトには、Orders 型の ordersCollection プロパティが含まれます。 このため、"型 'Orders' が定義されていません。" というメッセージが表示されます。 これは予期されたメッセージであり、次のセクションで Order クラスと Orders クラスを作成すると表示されなくなります。

    ''' <summary>
    ''' A single customer
    ''' </summary>
    Public Class Customer
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new customer
        ''' </summary>
        ''' <param name="customerId">The ID that uniquely identifies this customer</param>
        ''' <param name="companyName">The name for this customer</param>
        ''' <param name="contactName">The name for this customer's contact</param>
        ''' <param name="contactTitle">The title for this contact</param>
        ''' <param name="address">The address for this customer</param>
        ''' <param name="city">The city for this customer</param>
        ''' <param name="region">The region for this customer</param>
        ''' <param name="postalCode">The postal code for this customer</param>
        ''' <param name="country">The country for this customer</param>
        ''' <param name="phone">The phone number for this customer</param>
        ''' <param name="fax">The fax number for this customer</param>
        Public Sub New(ByVal customerId As String,
                       ByVal companyName As String,
                       ByVal contactName As String,
                       ByVal contactTitle As String,
                       ByVal address As String,
                       ByVal city As String,
                       ByVal region As String,
                       ByVal postalCode As String,
                       ByVal country As String,
                       ByVal phone As String,
                       ByVal fax As String)
            customerIDValue = customerId
            companyNameValue = companyName
            contactNameValue = contactName
            contactTitleValue = contactTitle
            addressValue = address
            cityValue = city
            regionValue = region
            postalCodeValue = postalCode
            countryValue = country
            phoneValue = phone
            faxValue = fax
        End Sub
    
        Private customerIDValue As String
        ''' <summary>
        ''' The ID that uniquely identifies this customer
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal value As String)
                customerIDValue = value
            End Set
        End Property
    
        Private companyNameValue As String
        ''' <summary>
        ''' The name for this customer
        ''' </summary>
        Public Property CompanyName() As String
            Get
                Return companyNameValue
            End Get
            Set(ByVal Value As String)
                companyNameValue = Value
            End Set
        End Property
    
        Private contactNameValue As String
        ''' <summary>
        ''' The name for this customer's contact
        ''' </summary>
        Public Property ContactName() As String
            Get
                Return contactNameValue
            End Get
            Set(ByVal Value As String)
                contactNameValue = Value
            End Set
        End Property
    
        Private contactTitleValue As String
        ''' <summary>
        ''' The title for this contact
        ''' </summary>
        Public Property ContactTitle() As String
            Get
                Return contactTitleValue
            End Get
            Set(ByVal Value As String)
                contactTitleValue = Value
            End Set
        End Property
    
        Private addressValue As String
        ''' <summary>
        ''' The address for this customer
        ''' </summary>
        Public Property Address() As String
            Get
                Return addressValue
            End Get
            Set(ByVal Value As String)
                addressValue = Value
            End Set
        End Property
    
        Private cityValue As String
        ''' <summary>
        ''' The city for this customer
        ''' </summary>
        Public Property City() As String
            Get
                Return cityValue
            End Get
            Set(ByVal Value As String)
                cityValue = Value
            End Set
        End Property
    
        Private regionValue As String
        ''' <summary>
        ''' The region for this customer
        ''' </summary>
        Public Property Region() As String
            Get
                Return regionValue
            End Get
            Set(ByVal Value As String)
                regionValue = Value
            End Set
        End Property
    
        Private postalCodeValue As String
        ''' <summary>
        ''' The postal code for this customer
        ''' </summary>
        Public Property PostalCode() As String
            Get
                Return postalCodeValue
            End Get
            Set(ByVal Value As String)
                postalCodeValue = Value
            End Set
        End Property
    
        Private countryValue As String
        ''' <summary>
        ''' The country for this customer
        ''' </summary>
        Public Property Country() As String
            Get
                Return countryValue
            End Get
            Set(ByVal Value As String)
                countryValue = Value
            End Set
        End Property
    
    
        Private phoneValue As String
        ''' <summary>
        ''' The phone number for this customer
        ''' </summary>
        Public Property Phone() As String
            Get
                Return phoneValue
            End Get
            Set(ByVal Value As String)
                phoneValue = Value
            End Set
        End Property
    
        Private faxValue As String
        ''' <summary>
        ''' The fax number for this customer
        ''' </summary>
        Public Property Fax() As String
            Get
                Return faxValue
            End Get
            Set(ByVal Value As String)
                faxValue = Value
            End Set
        End Property
    
        Private ordersCollection As New System.ComponentModel.BindingList(Of Order)
        ''' <summary>
        ''' The orders for this customer
        ''' </summary>
        Public Property Orders() As System.ComponentModel.BindingList(Of Order)
            Get
                Return ordersCollection
            End Get
            Set(ByVal value As System.ComponentModel.BindingList(Of Order))
                ordersCollection = value
            End Set
        End Property
    
    
        Public Overrides Function ToString() As String
            Return Me.CompanyName & " (" & Me.CustomerID & ")"
        End Function
    
    End Class
    
    namespace ObjectBindingWalkthrough
    {
        /// <summary>
        /// A single customer
        /// </summary>
        public class Customer
        {
            /// <summary>
            /// Creates a new customer
            /// </summary>
            public Customer()
            {
            }
    
            /// <summary>
            /// Creates a new customer
            /// </summary>
            /// <param name="customerID"></param>
            /// <param name="companyName"></param>
            /// <param name="contactName"></param>
            /// <param name="contactTitle"></param>
            /// <param name="address"></param>
            /// <param name="city"></param>
            /// <param name="region"></param>
            /// <param name="postalCode"></param>
            /// <param name="country"></param>
            /// <param name="phone"></param>
            /// <param name="fax"></param>
            public Customer(string customerID, string companyName,
               string contactName, string contactTitle,
               string address, string city, string region,
               string postalCode, string country,
               string phone, string fax)
            {
                customerIDValue = customerID;
            }
    
            private string customerIDValue;
            /// <summary>
            /// The ID that uniquely identifies this customer
            /// </summary>
            public string CustomerID
            {
                get { return customerIDValue; }
                set { customerIDValue = value; }
            }
    
            private string companyNameValue;
            /// <summary>
            /// The name for this customer
            /// </summary>
            public string CompanyName
            {
                get { return companyNameValue; }
                set { companyNameValue = value; }
            }
    
            private string contactNameValue;
            /// <summary>
            /// The name for this customer's contact
            /// </summary>
            public string ContactName
            {
                get { return contactNameValue; }
                set { contactNameValue = value; }
            }
    
            private string contactTitleValue;
            /// <summary>
            /// The title for this contact
            /// </summary>
            public string ContactTitle
            {
                get { return contactTitleValue; }
                set { contactTitleValue = value; }
            }
    
            private string addressValue;
            /// <summary>
            /// The address for this customer
            /// </summary>
            public string Address
            {
                get { return addressValue; }
                set { addressValue = value; }
            }
    
            private string cityValue;
            /// <summary>
            /// The city for this customer
            /// </summary>
            public string City
            {
                get { return cityValue; }
                set { cityValue = value; }
            }
    
            private string regionValue;
            /// <summary>
            /// The region for this customer
            /// </summary>
            public string Region
            {
                get { return regionValue; }
                set { regionValue = value; }
            }
    
            private string postalCodeValue;
            /// <summary>
            /// The postal code for this customer
            /// </summary>
            public string PostalCode
            {
                get { return postalCodeValue; }
                set { postalCodeValue = value; }
            }
    
            private string countryValue;
            /// <summary>
            /// The country for this customer
            /// </summary>
            public string Country
            {
                get { return countryValue; }
                set { countryValue = value; }
            }
    
            private string phoneValue;
            /// <summary>
            /// The phone number for this customer
            /// </summary>
            public string Phone
            {
                get { return phoneValue; }
                set { phoneValue = value; }
            }
    
            private string faxValue;
            /// <summary>
            /// The fax number for this customer
            /// </summary>
            public string Fax
            {
                get { return faxValue; }
                set { faxValue = value; }
            }
    
            private System.ComponentModel.BindingList<Order> ordersCollection = 
                new System.ComponentModel.BindingList<Order>();
    
            public System.ComponentModel.BindingList<Order> Orders
            {
                get { return ordersCollection; }
                set { ordersCollection = value; }
            }
    
            public override string ToString()
            {
                return this.CompanyName + " (" + this.CustomerID + ")";
            }
        }
    }
    

Order オブジェクトの作成

Order オブジェクトと Orders コレクションを作成するには

  1. [プロジェクト] メニューの [クラスの追加] を選択します。

  2. 新しいクラスに「Order」という名前を付け、[追加] をクリックします。

  3. Order クラス ファイルのコードを次のコードで置き換えます。

    ''' <summary>
    ''' A single order
    ''' </summary>
    Public Class Order
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new order
        ''' </summary>
        ''' <param name="orderid">The identifier for this order</param>
        ''' <param name="customerID">The customer who placed this order</param>
        ''' <param name="employeeID">The ID of the employee who took this order</param>
        ''' <param name="orderDate">The date this order was placed</param>
        ''' <param name="requiredDate">The date this order is required</param>
        ''' <param name="shippedDate">The date the order was shipped</param>
        ''' <param name="shipVia">The shipping method for this order</param>
        ''' <param name="freight">The freight charge for this order</param>
        ''' <param name="shipName">The name of the recipient for this order</param>
        ''' <param name="shipAddress">The address to ship this order to</param>
        ''' <param name="shipCity">The city to ship this order to</param>
        ''' <param name="shipRegion">The region to ship this order to</param>
        ''' <param name="shipPostalCode">The postal code to ship this order to</param>
        ''' <param name="shipCountry">The country to ship this order to</param>
        Public Sub New(ByVal orderid As Integer,
                       ByVal customerID As String,
                       ByVal employeeID As Nullable(Of Integer),
                       ByVal orderDate As Nullable(Of DateTime),
                       ByVal requiredDate As Nullable(Of DateTime),
                       ByVal shippedDate As Nullable(Of DateTime),
                       ByVal shipVia As Nullable(Of Integer),
                       ByVal freight As Nullable(Of Decimal),
                       ByVal shipName As String,
                       ByVal shipAddress As String,
                       ByVal shipCity As String,
                       ByVal shipRegion As String,
                       ByVal shipPostalCode As String,
                       ByVal shipCountry As String)
            orderIDValue = orderid
            customerIDValue = customerID
            employeeIDValue = employeeID
            orderDateValue = orderDate
            requiredDateValue = requiredDate
            shippedDateValue = shippedDate
            shipViaValue = shipVia
            freightValue = freight
            shipAddressValue = shipAddress
            shipCityValue = shipCity
            shipRegionValue = shipRegion
            shipPostalCodeValue = shipPostalCode
            shipCountryValue = shipCountry
        End Sub
    
        Private orderIDValue As Integer
        ''' <summary>
        ''' Identifier for this order
        ''' </summary>
        Public Property OrderID() As Integer
            Get
                Return orderIDValue
            End Get
            Set(ByVal value As Integer)
                orderIDValue = value
            End Set
        End Property
    
        Private customerIDValue As String
        ''' <summary>
        ''' The customer who placed this order
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal Value As String)
                customerIDValue = Value
            End Set
        End Property
    
        Private employeeIDValue As Nullable(Of Integer)
        ''' <summary>
        ''' The ID of the employee who took this order
        ''' </summary>
        Public Property EmployeeID() As Nullable(Of Integer)
            Get
                Return employeeIDValue
            End Get
            Set(ByVal Value As Nullable(Of Integer))
                employeeIDValue = Value
            End Set
        End Property
    
    
        Private orderDateValue As Nullable(Of DateTime)
    
        ''' <summary>
        ''' The date this order was placed
        ''' </summary>
        Public Property OrderDate() As Nullable(Of DateTime)
            Get
                Return orderDateValue
            End Get
            Set(ByVal Value As Nullable(Of DateTime))
                orderDateValue = Value
            End Set
        End Property
    
        Private requiredDateValue As Nullable(Of DateTime)
        ''' <summary>
        ''' The date this order is required
        ''' </summary>
        Public Property RequiredDate() As Nullable(Of DateTime)
            Get
                Return requiredDateValue
            End Get
            Set(ByVal Value As Nullable(Of DateTime))
                requiredDateValue = Value
            End Set
        End Property
    
    
        Private shippedDateValue As Nullable(Of DateTime)
        ''' <summary>
        ''' The date this order was shipped
        ''' </summary>
        Public Property ShippedDate() As Nullable(Of DateTime)
            Get
                Return shippedDateValue
            End Get
            Set(ByVal Value As Nullable(Of DateTime))
                shippedDateValue = Value
            End Set
        End Property
    
        Private shipViaValue As Nullable(Of Integer)
        ''' <summary>
        ''' The shipping method for this order
        ''' </summary>
        Public Property ShipVia() As Nullable(Of Integer)
            Get
                Return shipViaValue
            End Get
            Set(ByVal Value As Nullable(Of Integer))
                shipViaValue = Value
            End Set
        End Property
    
    
        Private freightValue As Nullable(Of Decimal)
        ''' <summary>
        ''' The freight charge for this order
        ''' </summary>
        Public Property Freight() As Nullable(Of Decimal)
            Get
                Return freightValue
            End Get
            Set(ByVal Value As Nullable(Of Decimal))
                freightValue = Value
            End Set
        End Property
    
        Private shipNameValue As String
        ''' <summary>
        ''' The name of the recipient for this order
        ''' </summary>
        Public Property ShipName() As String
            Get
                Return shipNameValue
            End Get
            Set(ByVal Value As String)
                shipNameValue = Value
            End Set
        End Property
    
    
        Private shipAddressValue As String
        ''' <summary>
        ''' The address to ship this order to
        ''' </summary>
        Public Property ShipAddress() As String
            Get
                Return shipAddressValue
            End Get
            Set(ByVal Value As String)
                shipAddressValue = Value
            End Set
        End Property
    
        Private shipCityValue As String
        ''' <summary>
        ''' The city to ship this order to
        ''' </summary>
        Public Property ShipCity() As String
            Get
                Return shipCityValue
            End Get
            Set(ByVal Value As String)
                shipCityValue = Value
            End Set
        End Property
    
        Private shipRegionValue As String
        ''' <summary>
        ''' The region to ship this order to
        ''' </summary>
        Public Property ShipRegion() As String
            Get
                Return shipRegionValue
            End Get
            Set(ByVal Value As String)
                shipRegionValue = Value
            End Set
        End Property
    
        Private shipPostalCodeValue As String
        ''' <summary>
        ''' The postal code to ship this order to
        ''' </summary>
        Public Property ShipPostalCode() As String
            Get
                Return shipPostalCodeValue
            End Get
            Set(ByVal Value As String)
                shipPostalCodeValue = Value
            End Set
        End Property
    
        Private shipCountryValue As String
        ''' <summary>
        ''' The country to ship this order to
        ''' </summary>
        Public Property ShipCountry() As String
            Get
                Return shipCountryValue
            End Get
            Set(ByVal Value As String)
                shipCountryValue = Value
            End Set
        End Property
    
    
        Private customerValue As Customer
        ''' <summary>
        ''' The customer this order belongs to
        ''' </summary>
        Public Property Customer() As Customer
            Get
                Return customerValue
            End Get
            Set(ByVal Value As Customer)
                customerValue = Value
            End Set
        End Property
    
    
    End Class
    
    ''' <summary>
    ''' A collection of Orders
    ''' </summary>
    Public Class Orders
        Inherits System.ComponentModel.BindingList(Of Order)
    
    End Class
    
    using System;
    
    namespace ObjectBindingWalkthrough
    {
        /// <summary>
        /// A single order
        /// </summary>
        public class Order
        {
            /// <summary>
            /// Creates a new order
            /// </summary>
            public Order()
            {
            }
    
            /// <summary>
            /// Creates a new order
            /// </summary>
            /// <param name="orderid"></param>
            /// <param name="customerID"></param>
            /// <param name="employeeID"></param>
            /// <param name="orderDate"></param>
            /// <param name="requiredDate"></param>
            /// <param name="shippedDate"></param>
            /// <param name="shipVia"></param>
            /// <param name="freight"></param>
            /// <param name="shipName"></param>
            /// <param name="shipAddress"></param>
            /// <param name="shipCity"></param>
            /// <param name="shipRegion"></param>
            /// <param name="shipPostalCode"></param>
            /// <param name="shipCountry"></param>
            public Order(int orderid, string customerID,
               Nullable<int> employeeID, Nullable<DateTime> orderDate,
               Nullable<DateTime> requiredDate, Nullable<DateTime> shippedDate,
               Nullable<int> shipVia, Nullable<decimal> freight,
               string shipName, string shipAddress,
               string shipCity, string shipRegion,
               string shipPostalCode, string shipCountry)
            {
    
            }
    
            private int orderIDValue;
            /// <summary>
            /// The ID that uniquely identifies this order
            /// </summary>
            public int OrderID
            {
                get { return orderIDValue; }
                set { orderIDValue = value; }
            }
    
            private string customerIDValue;
            /// <summary>
            /// The customer who placed this order
            /// </summary>
            public string CustomerID
            {
                get { return customerIDValue; }
                set { customerIDValue = value; }
            }
    
            private Nullable<int> employeeIDValue;
            /// <summary>
            /// The ID of the employee who took this order
            /// </summary>
            public Nullable<int> EmployeeID
            {
                get { return employeeIDValue; }
                set { employeeIDValue = value; }
            }
    
            private Nullable<DateTime> orderDateValue;
            /// <summary>
            /// The date this order was placed
            /// </summary>
            public Nullable<DateTime> OrderDate
            {
                get { return orderDateValue; }
                set { orderDateValue = value; }
            }
    
            private Nullable<DateTime> requiredDateValue;
            /// <summary>
            /// The date this order is required
            /// </summary>
            public Nullable<DateTime> RequiredDate
            {
                get { return requiredDateValue; }
                set { requiredDateValue = value; }
            }
    
            private Nullable<DateTime> shippedDateValue;
            /// <summary>
            /// The date this order was shipped
            /// </summary>
            public Nullable<DateTime> ShippedDate
            {
                get { return shippedDateValue; }
                set { shippedDateValue = value; }
            }
    
            private Nullable<int> shipViaValue;
            /// <summary>
            /// The shipping method of this order
            /// </summary>
            public Nullable<int> ShipVia
            {
                get { return shipViaValue; }
                set { shipViaValue = value; }
            }
    
            private Nullable<decimal> freightValue;
            /// <summary>
            /// The freight charge for this order
            /// </summary>
            public Nullable<decimal> Freight
            {
                get { return freightValue; }
                set { freightValue = value; }
            }
    
            private string shipNameValue;
            /// <summary>
            /// The name of the recipient for this order
            /// </summary>
            public string ShipName
            {
                get { return shipNameValue; }
                set { shipNameValue = value; }
            }
    
            private string shipAddressValue;
            /// <summary>
            /// The address to ship this order to
            /// </summary>
            public string ShipAddress
            {
                get { return shipAddressValue; }
                set { shipAddressValue = value; }
            }
    
            private string shipCityValue;
            /// <summary>
            /// The city to ship this order to
            /// </summary>
            public string ShipCity
            {
                get { return shipCityValue; }
                set { shipCityValue = value; }
            }
    
            private string shipRegionValue;
            /// <summary>
            /// The region to ship this order to
            /// </summary>
            public string ShipRegion
            {
                get { return shipRegionValue; }
                set { shipRegionValue = value; }
            }
    
            private string shipPostalCodeValue;
            /// <summary>
            /// The postal code to ship this order to
            /// </summary>
            public string ShipPostalCode
            {
                get { return shipPostalCodeValue; }
                set { shipPostalCodeValue = value; }
            }
    
            private string shipCountryValue;
            /// <summary>
            /// The country to ship this order to
            /// </summary>
            public string ShipCountry
            {
                get { return shipCountryValue; }
                set { shipCountryValue = value; }
            }
    
        }
    
    
        /// <summary>
        /// A collection of Order objects
        /// </summary>
        class Orders : System.ComponentModel.BindingList<Order>
        {
    
        }
    }
    
  4. [ファイル] メニューの [すべてを保存] をクリックします。

オブジェクト データ ソースの作成

データ ソース構成ウィザードを実行し、前の手順で作成したオブジェクトに基づいてデータ ソースを作成できます。

オブジェクト データ ソースを作成するには

  1. プロジェクトをビルドします。

    注意

    プロジェクトのオブジェクトをデータ ソース構成ウィザードで選択できるようにするには、プロジェクトをビルドする必要があります。

  2. [データ] メニューの [データ ソースの表示] をクリックして、[データ ソース] ウィンドウを開きます。

  3. [データ ソース] ウィンドウの [新しいデータ ソースの追加] をクリックします。

    データ ソース構成ウィザードが開始します。

  4. [データ ソースの種類を選択] ページで、[オブジェクト] を選択し、[次へ] をクリックします。

  5. [データ オブジェクトの選択] ページで、[ObjectBindingWalkthrough] ノードを展開し、[Customer] オブジェクトの横にあるチェック ボックスをオンにします。

  6. [完了] をクリックします。

    [データ ソース] ウィンドウに Customer オブジェクトが表示されます。

データ バインド フォームの作成

[データ ソース] ウィンドウからフォームに項目をドラッグすると、Customer オブジェクトにバインドされたコントロールが作成されます。

オブジェクト プロパティにバインドされたコントロールを持つフォームを作成するには

  1. ソリューション エクスプローラーForm1 を選択し、[デザイナーの表示] をクリックします。

  2. [データ ソース] ウィンドウから Form1[Customer] ノードをドラッグします。

  3. [Customer] ノードを展開し、[Orders] ノードを [データ ソース] ウィンドウから Form1 にドラッグします。

データをデータベースからカスタム オブジェクトに読み込むための TableAdapters の作成

オブジェクトとデータベースの間でデータを移動するには、TableAdapter を使用します。 データ ソース構成ウィザードを使用して、TableAdapter を Customers テーブルと Orders テーブルに作成できます。

TableAdapter を作成するには

  1. [データ] メニューの [新しいデータ ソースの追加] をクリックします。

  2. [データソースの種類を選択] ページで、[データベース] を選択し、[次へ] をクリックします。

  3. [データベース モデルの選択] ページで、[データセット] を選択し、[次へ] をクリックします。

  4. [データ接続の選択] ページで、次のいずれかの手順を実行します。

    • Northwind サンプル データベースへのデータ接続がドロップダウン リストに表示されている場合は選択します。

      または

    • [新しい接続] を選択し、Northwind データベースへの新しいデータ接続を構成します。 詳細については、「方法 : データベース内のデータに接続する」を参照してください。

  5. データ接続を選択したら、[次へ] をクリックします。

  6. [アプリケーション構成ファイルに接続文字列を保存] ページで、[次へ] をクリックします。

  7. [データベース オブジェクトの選択] ページで、[テーブル] ノードを展開します。

  8. Customers テーブルと Orders テーブルを選択し、[完了] をクリックします。

    プロジェクトに NorthwindDataSet が追加され、[データ ソース] ウィンドウの [NorthwindDataSet] ノードの下に Customers テーブルと Orders テーブルが表示されます。

データセットと TableAdapter の Form1 への追加

CustomersTableAdapter、OrdersTableAdapter、および NorthwindDataSet を表すコンポーネントをツールボックスからドラッグして、これらのインスタンスをフォームに追加できます。

Customers テーブルのデータを Customer オブジェクトに設定するには

  1. [ビルド] メニューの [ソリューションのビルド] をクリックします。

  2. ツールボックスから Form1NorthwindDataSet をドラッグします。

  3. ツールボックスから Form1CustomersTableAdapter をドラッグします。

  4. ツールボックスから Form1OrdersTableAdapter をドラッグします。

少数の Customer を返すクエリの CustomersTableAdapter への追加

実際のアプリケーションでは、データ テーブルの全体を返すことはまずありません。 このチュートリアルでは、上から 5 番目までの顧客を返します。

注意

通常は、どの顧客を返すか選択するためにパラメーターを渡すことが多いのですが、このチュートリアルでは説明を簡単にするために 5 人の顧客だけを返すクエリをハードコーディングして、パラメーター値を入力するためのユーザー インターフェイスの作成を省いています。

CustomersTableAdapter に別のクエリを追加するには

  1. ソリューション エクスプローラーで、NorthwindDataSet.xsd ファイルをダブルクリックします。

    データセット デザイナーNorthwindDataSet が開きます。

  2. [CustomersTableAdapter] を右クリックし、[クエリの追加] を選択します。

    TableAdapter クエリの構成ウィザードが表示されます。

  3. 既定の [SQL ステートメントを使用する] はそのままで、[次へ] をクリックします。

  4. 既定の [複数行を返す SELECT] はそのままで、[次へ] をクリックします。

  5. SQL ステートメントを次のコードに置き換え、[次へ] をクリックします。

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. [DataTable にデータを格納する] チェック ボックスをオフにします。

  7. [DataTable を返す] メソッドに「GetTop5Customers」という名前を付け、[完了] をクリックします。

    GetTop5Customers クエリが CustomersTableAdapter に追加されます。

特定の顧客の注文のみを返す OrdersTableAdapter クエリの変更

データベースから注文をフェッチするときに、注文テーブル全体を返すのではなく、特定の顧客の注文のみを返す必要があります。 次の手順は、TableAdapter を新しいクエリで再構成する方法を示しています。前の手順で CustomersTableAdapter に別のクエリを追加した方法とは対照的です。

1 人の顧客からの注文を返すように TableAdapter のメイン クエリを再構成するには

  1. [OrdersTableAdapter] を右クリックし、[構成] をクリックします。

    TableAdapter クエリの構成ウィザードが表示されます。

  2. SQL ステートメントを次のコードに置き換え、[次へ] をクリックします。

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. [DataTable にデータを格納する] チェック ボックスをオフにします。

  4. [DataTable を返す] メソッドに「GetDataByCustomerID」という名前を付け、[完了] をクリックします。

    OrdersTableAdapter のメイン Fill クエリが、GetDataByCustomerID クエリで置き換えられます。

  5. [ビルド] メニューの [ソリューションのビルド] をクリックして、プロジェクトをビルドします。

データを Customer オブジェクトと Order オブジェクトに読み込むためのコードの追加

データをカスタム オブジェクトに読み込むには、既存のデータ テーブルにデータを設定する TableAdapter クエリを使用するのではなく、新しいデータ テーブルを返す TableAdapter クエリを実行します。 その後、コードでテーブルをループ処理し、各 Customer オブジェクトに顧客情報を設定し、各 Customer.Orders コレクションにすべての注文を設定します。 各 Customer オブジェクトが CustomerBindingSource の内部コレクションに追加されるしくみ (CustomerBindingSource.Add(currentCustomer)) に注目してください。 BindingSource には、List プロパティを通じてアクセスできる、厳密に型指定された組み込みのコレクションである Customers が用意されています。

オブジェクトにデータを読み込むには

  1. ソリューション エクスプローラーForm1 を選択し、[コードの表示] をクリックします。

  2. Form1 のコードを次のコードで置き換えます。

    Public Class Form1
        Private Sub LoadCustomers()
            Dim customerData As NorthwindDataSet.CustomersDataTable =
                CustomersTableAdapter1.GetTop5Customers()
    
            Dim customerRow As NorthwindDataSet.CustomersRow
    
            For Each customerRow In customerData
                Dim currentCustomer As New Customer()
                With currentCustomer
    
                    .CustomerID = customerRow.CustomerID
                    .CompanyName = customerRow.CompanyName
    
                    If Not customerRow.IsAddressNull Then
                        .Address = customerRow.Address
                    End If
    
                    If Not customerRow.IsCityNull Then
                        .City = customerRow.City
                    End If
    
                    If Not customerRow.IsContactNameNull Then
                        .ContactName = customerRow.ContactName
                    End If
    
                    If Not customerRow.IsContactTitleNull Then
                        .ContactTitle = customerRow.ContactTitle
                    End If
    
                    If Not customerRow.IsCountryNull Then
                        .Country = customerRow.Country
                    End If
    
                    If Not customerRow.IsFaxNull Then
                        .Fax = customerRow.Fax
                    End If
    
                    If Not customerRow.IsPhoneNull Then
                        .Phone = customerRow.Phone
                    End If
    
                    If Not customerRow.IsPostalCodeNull Then
                        .PostalCode = customerRow.PostalCode
                    End If
    
                    If Not customerRow.Is_RegionNull Then
                        .Region = customerRow._Region
                    End If
    
                End With
    
                LoadOrders(currentCustomer)
                CustomerBindingSource.Add(currentCustomer)
            Next
        End Sub
    
        Private Sub LoadOrders(ByRef currentCustomer As Customer)
            Dim orderData As NorthwindDataSet.OrdersDataTable =
                OrdersTableAdapter1.GetDataByCustomerID(currentCustomer.CustomerID)
    
            Dim orderRow As NorthwindDataSet.OrdersRow
    
            For Each orderRow In orderData
                Dim currentOrder As New Order()
                With currentOrder
                    .OrderID = orderRow.OrderID
                    .Customer = currentCustomer
    
                    If Not orderRow.IsCustomerIDNull Then
                        .CustomerID = orderRow.CustomerID
                    End If
    
                    If Not orderRow.IsEmployeeIDNull Then
                        .EmployeeID = orderRow.EmployeeID
                    End If
    
                    If Not orderRow.IsFreightNull Then
                        .Freight = orderRow.Freight
                    End If
    
                    If Not orderRow.IsOrderDateNull Then
                        .OrderDate = orderRow.OrderDate
                    End If
    
                    If Not orderRow.IsRequiredDateNull Then
                        .RequiredDate = orderRow.RequiredDate
                    End If
    
                    If Not orderRow.IsShipAddressNull Then
                        .ShipAddress = orderRow.ShipAddress
                    End If
    
                    If Not orderRow.IsShipCityNull Then
                        .ShipCity = orderRow.ShipCity
                    End If
    
                    If Not orderRow.IsShipCountryNull Then
                        .ShipCountry = orderRow.ShipCountry
                    End If
    
                    If Not orderRow.IsShipNameNull Then
                        .ShipName = orderRow.ShipName
                    End If
    
                    If Not orderRow.IsShippedDateNull Then
                        .ShippedDate = orderRow.ShippedDate
                    End If
    
                    If Not orderRow.IsShipPostalCodeNull Then
                        .ShipPostalCode = orderRow.ShipPostalCode
                    End If
    
                    If Not orderRow.IsShipRegionNull Then
                        .ShipRegion = orderRow.ShipRegion
                    End If
    
                    If Not orderRow.IsShipViaNull Then
                        .ShipVia = orderRow.ShipVia
                    End If
                End With
                currentCustomer.Orders.Add(currentOrder)
            Next
    
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, 
                               ByVal e As System.EventArgs) Handles MyBase.Load
    
            LoadCustomers()
        End Sub
    End Class
    
    using System;
    using System.Windows.Forms;
    
    namespace ObjectBindingWalkthrough
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.Load += Form1_Load;
            }
    
            private void LoadCustomers()
            {
                NorthwindDataSet.CustomersDataTable customerData = 
                    customersTableAdapter1.GetTop5Customers();
    
                foreach (NorthwindDataSet.CustomersRow customerRow in customerData)
                {
                    Customer currentCustomer = new Customer();
                    currentCustomer.CustomerID = customerRow.CustomerID;
                    currentCustomer.CompanyName = customerRow.CompanyName;
    
                    if (customerRow.IsAddressNull() == false)
                    {
                        currentCustomer.Address = customerRow.Address;
                    }
    
                    if (customerRow.IsCityNull() == false)
                    {
                        currentCustomer.City = customerRow.City;
                    }
    
                    if (customerRow.IsContactNameNull() == false)
                    {
                        currentCustomer.ContactName = customerRow.ContactName;
                    }
    
                    if (customerRow.IsContactTitleNull() == false)
                    {
                        currentCustomer.ContactTitle = customerRow.ContactTitle;
                    }
    
                    if (customerRow.IsCountryNull() == false)
                    {
                        currentCustomer.Country = customerRow.Country;
                    }
    
                    if (customerRow.IsFaxNull() == false)
                    {
                        currentCustomer.Fax = customerRow.Fax;
                    }
    
                    if (customerRow.IsPhoneNull() == false)
                    {
                        currentCustomer.Phone = customerRow.Phone;
                    }
    
                    if (customerRow.IsPostalCodeNull() == false)
                    {
                        currentCustomer.PostalCode = customerRow.PostalCode;
                    }
    
                    if (customerRow.IsRegionNull() == false)
                    {
                        currentCustomer.Region = customerRow.Region;
                    }
    
                    LoadOrders(currentCustomer);
                    customerBindingSource.Add(currentCustomer);
                }
            }
    
    
            private void LoadOrders(Customer currentCustomer)
            {
                NorthwindDataSet.OrdersDataTable orderData = 
                    ordersTableAdapter1.GetDataByCustomerID(currentCustomer.CustomerID);
    
                foreach (NorthwindDataSet.OrdersRow orderRow in orderData)
                {
                    Order currentOrder = new Order();
                    currentOrder.OrderID = orderRow.OrderID;
    
                    if (orderRow.IsCustomerIDNull() == false)
                    {
                        currentOrder.CustomerID = orderRow.CustomerID;
                    }
    
                    if (orderRow.IsEmployeeIDNull() == false)
                    {
                        currentOrder.EmployeeID = orderRow.EmployeeID;
                    }
    
                    if (orderRow.IsFreightNull() == false)
                    {
                        currentOrder.Freight = orderRow.Freight;
                    }
    
                    if (orderRow.IsOrderDateNull() == false)
                    {
                        currentOrder.OrderDate = orderRow.OrderDate;
                    }
    
                    if (orderRow.IsRequiredDateNull() == false)
                    {
                        currentOrder.RequiredDate = orderRow.RequiredDate;
                    }
    
                    if (orderRow.IsShipAddressNull() == false)
                    {
                        currentOrder.ShipAddress = orderRow.ShipAddress;
                    }
    
                    if (orderRow.IsShipCityNull() == false)
                    {
                        currentOrder.ShipCity = orderRow.ShipCity;
                    }
    
                    if (orderRow.IsShipCountryNull() == false)
                    {
                        currentOrder.ShipCountry = orderRow.ShipCountry;
                    }
    
                    if (orderRow.IsShipNameNull() == false)
                    {
                        currentOrder.ShipName = orderRow.ShipName;
                    }
    
                    if (orderRow.IsShippedDateNull() == false)
                    {
                        currentOrder.ShippedDate = orderRow.ShippedDate;
                    }
    
                    if (orderRow.IsShipPostalCodeNull() == false)
                    {
                        currentOrder.ShipPostalCode = orderRow.ShipPostalCode;
                    }
    
                    if (orderRow.IsShipRegionNull() == false)
                    {
                        currentOrder.ShipRegion = orderRow.ShipRegion;
                    }
    
                    if (orderRow.IsShipViaNull() == false)
                    {
                        currentOrder.ShipVia = orderRow.ShipVia;
                    }
                    currentCustomer.Orders.Add(currentOrder);
                }
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                LoadCustomers();
            }
    
        }
    }
    

アプリケーションのテスト

アプリケーションをテストするには

  1. F5 キーを押してアプリケーションを実行します。

  2. フォームが開き、サンプル データで DataGridView コントロールが作成されます。

  3. DataGridView の顧客に移動し、その顧客からの注文を表示します。

次の手順

アプリケーションに機能を追加するには

参照

概念

Visual Studio でのデータへのコントロールのバインド

Visual Studio におけるオブジェクトのバインド

その他の技術情報

Visual Studio でのデータへの接続

アプリケーションでデータを受け取る準備

アプリケーションへのデータのフェッチ

アプリケーションでのデータ編集

データの保存

データに関するチュートリアル