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

更新 : 2007 年 11 月

Visual Studio は、アプリケーションのデータ ソースとして使用するカスタム オブジェクト (データセットや Web サービスではなく) を操作するためのデザイン時ツールを提供します。

Visual Studio のデータ デザイン ツールでカスタム オブジェクトを使用するために必要な唯一の要件は、オブジェクトに少なくとも 1 つのパブリック プロパティが必要であることです。カスタム オブジェクトを [データ ソース] ウィンドウなどのツールで使用するために特定のコンストラクタや属性は必要ありません。

オブジェクトをデータ ソースとして使用する際にアプリケーション ロジックを実装する方法は多数ありますが、新しい Visual Studio が生成する TableAdapter オブジェクトを使用することによって簡素化できる標準的な方法がいくつかあります。このページでは、TableAdapter を使用して標準的なプロセスを実装する方法について説明しますが、カスタム オブジェクトを作成するためのガイドは意図していません。たとえば、オブジェクトまたはアプリケーションのロジックの実装にかかわらず、一般に次の標準的な操作を実行できます。

  • オブジェクトへのデータの読み込み (通常はデータベースより)

  • 型指定されたオブジェクトのコレクションの作成

  • コレクションへのオブジェクトの追加および削除

  • ユーザーのフォームへのオブジェクト データの表示

  • オブジェクトのデータの変更または編集

  • オブジェクトからデータベースにデータを戻して保存する

メモ :

このページの例をより良く理解するために、「チュートリアル : オブジェクトのデータへの接続」を完了することをお勧めします。このチュートリアルでは、このヘルプ ページで説明するオブジェクトを作成します。

オブジェクトへのデータの読み込み

この例では、TableAdapter を使用してオブジェクトにデータを読み込みます。既定では、TableAdapter はデータベースからデータを取得するメソッドとデータ テーブルにデータを設定するメソッドの 2 種類のメソッドで作成されます。

  • TableAdapter.Fill メソッドは、返されたデータを既存のデータ テーブルに読み込みます。

  • TableAdapter.GetData メソッドは、データを読み込んだ新しいデータ テーブルを返します。

カスタム オブジェクトにデータを最も簡単に読み込む方法は TableAdapter.GetData メソッドを呼び出し、返されたデータ テーブルの行のコレクションを反復処理し、各オブジェクトに各行の値を設定することです。TableAdapter に追加されたクエリにデータ入力されたデータ テーブルを返す GetData メソッドを作成できます。

メモ :

Visual Studio は既定で TableAdapter のクエリに Fill と GetData という名前を付けていますが、この名前は任意の有効なメソッド名に変更できます。

データ テーブルの行を反復処理し、オブジェクトにデータを設定する方法の例を次に示します。

完全なコード例については、「チュートリアル : オブジェクトのデータへの接続」を参照してください。

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 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);
    }
}

型指定されたオブジェクトのコレクションの作成

オブジェクトにはコレクションのクラスを作成するか、または BindingSource コンポーネント が自動的に提供する型指定されたコレクションを使用できます。

オブジェクトのためにカスタムのコレクション クラスを作成する場合は、BindingList<T> から継承することをお勧めします。このジェネリック クラスは、Windows フォームのデータ バインド インフラストラクチャに通知を送信するイベントを発生する機能と共にコレクションを管理するための機能を提供します。

BindingSource で自動生成されるコレクションは、型指定されたコレクションに BindingList<T> を使用します。アプリケーションが追加機能を必要としない場合は、BindingSource 内でコレクションを維持できます。詳細については、BindingSource クラスの List プロパティを参照してください。

メモ :

コレクションが BindingList<T> の基本実装が提供していない機能を必要とする場合は、必要に応じてカスタム コレクションを作成してクラスに追加する必要があります。

Order オブジェクトの厳密に型指定されたコレクションのクラスを作成する方法のコード例を次に示します。

''' <summary>
''' A collection of Orders
''' </summary>
Public Class Orders
    Inherits System.ComponentModel.BindingList(Of Order)

    ' Add any additional functionality required by your collection.

End Class
/// <summary>
/// A collection of Orders
/// </summary>
public class Orders: System.ComponentModel.BindingList<Order>
{
    // Add any additional functionality required by your collection.
}

コレクションへのオブジェクトの追加

オブジェクトをコレクションに追加する場合は、カスタム コレクション クラスまたは BindingSource の Add メソッドを呼び出します。

BindingSource を使用してコレクションを追加する例については、「チュートリアル : オブジェクトのデータへの接続」の LoadCustomers メソッドを参照してください。

オブジェクトをカスタム コレクションを追加する例については、「チュートリアル : オブジェクトのデータへの接続」の LoadOrders メソッドを参照してください。

メモ :

BindingList<T> から継承する場合、Add メソッドは自動的にカスタム コレクションに提供されます。

BindingSource の型指定されたコレクションにオブジェクトを追加する方法のコード例を次に示します。

Dim currentCustomer As New Customer()
CustomerBindingSource.Add(currentCustomer)
Customer currentCustomer = new Customer();
customerBindingSource.Add(currentCustomer);

BindingList<T> から継承された型指定されたコレクションにオブジェクトを追加する方法のコード例を次に示します。

メモ :

この例では、Orders コレクションは Customer オブジェクトのプロパティです。

Dim currentOrder As New Order()
currentCustomer.Orders.Add(currentOrder)
Order currentOrder = new Order();
currentCustomer.Orders.Add(currentOrder);

コレクションからのオブジェクトの削除

コレクションからオブジェクトを削除する場合は、カスタム コレクション クラスまたは BindingSource の Remove メソッドまたは RemoveAt メソッドを呼び出します。

メモ :

Remove メソッドと RemoveAt メソッドは、BindingList<T> から継承する際にカスタム コレクションに自動的に提供されます。

RemoveAt メソッドを使用して BindingSource の型指定されたコレクションからオブジェクトを探して削除する方法のコード例を次に示します。

Dim customerIndex As Integer = CustomerBindingSource.Find("CustomerID", "ALFKI")
CustomerBindingSource.RemoveAt(customerIndex)
int customerIndex = customerBindingSource.Find("CustomerID", "ALFKI");
customerBindingSource.RemoveAt(customerIndex);

ユーザーへのオブジェクト データの表示

オブジェクトのデータをユーザーに表示するには、データ ソース構成ウィザード を使用してオブジェクト データ ソースを作成し、次に [データ ソース] ウィンドウからフォームにオブジェクト全体または個々のプロパティをドラッグします。

オブジェクト データ ソースの作成の詳細については、「方法 : オブジェクトのデータに接続する」を参照してください。

オブジェクトから Windows フォームへのデータの表示の詳細については、「Windows アプリケーションのフォームでのデータの表示」を参照してください。

オブジェクトのデータの変更

Windows フォーム コントロールにデータ バインドされたカスタム オブジェクトのデータを編集するには、単にバインドされたコントロールのデータを編集するか、またはオブジェクトのプロパティを直接編集します。データ バインディング アーキテクチャがオブジェクトのデータを更新します。

アプリケーションで変更内容を追跡し、指定した変更を元の値にロールバックする必要がある場合は、オブジェクト モデルにこの機能を実装する必要があります。データ テーブルで指定した変更内容を追跡する方法の例については、「DataRowState」、「HasChanges」、および「GetChanges」を参照してください。

オブジェクトのデータをデータベースに戻して保存する

オブジェクトのデータは、オブジェクトから値を TableAdapter の DBDirect のメソッドに渡すことによってデータベースに戻して保存します。

Visual Studio は、データベースに対して直接実行できる DBDirect のメソッドを作成します。この一連のメソッドは、DataSet オブジェクトや DataTable オブジェクトを必要としません。

TableAdapter DBDirect のメソッド

説明

TableAdapter.Insert

個々の列値をメソッド パラメータとして渡して、新しいレコードをデータベースに追加します。

TableAdapter.Update

データベースの既存のレコードを更新します。Update メソッドは、元の列値と新しい列値をメソッド パラメータとして受け取ります。元の値は元のレコードを探すために使用し、新しい値はレコードを更新するために使用します。

TableAdapter.Update メソッドも DataSetDataTableDataRow、または DataRow の配列をメソッド パラメータとして受け取って、データセットの変更内容をデータベースに反映して戻すために使用します。

TableAdapter.Delete

メソッド パラメータとして渡された元の列値に基づいてデータベースから既存のレコードを削除します。

オブジェクトのコレクションからデータを保存するには、for-next ループなどを使用してオブジェクトのコレクションを反復処理し、TableAdapter の DBDirect のメソッドを使用して各オブジェクトの値をデータベースに送ります。

TableAdapter.Insert DBDirect メソッドを使用して、新しい顧客を直接データベースに追加する方法の例を次に示します。

Private Sub AddNewCustomer(ByVal currentCustomer As Customer)

    CustomersTableAdapter.Insert( _
        currentCustomer.CustomerID, _
        currentCustomer.CompanyName, _
        currentCustomer.ContactName, _
        currentCustomer.ContactTitle, _
        currentCustomer.Address, _
        currentCustomer.City, _
        currentCustomer.Region, _
        currentCustomer.PostalCode, _
        currentCustomer.Country, _
        currentCustomer.Phone, _
        currentCustomer.Fax)
End Sub
private void AddNewCustomers(Customer currentCustomer)
{
    customersTableAdapter.Insert( 
        currentCustomer.CustomerID, 
        currentCustomer.CompanyName, 
        currentCustomer.ContactName, 
        currentCustomer.ContactTitle, 
        currentCustomer.Address, 
        currentCustomer.City, 
        currentCustomer.Region, 
        currentCustomer.PostalCode, 
        currentCustomer.Country, 
        currentCustomer.Phone, 
        currentCustomer.Fax);
}

参照

処理手順

方法 : オブジェクトのデータに接続する

チュートリアル : オブジェクトのデータへの接続

方法 : オブジェクトからデータベースにデータを保存する

方法 : TableAdapter で直接データベースにアクセスする

チュートリアル : TableAdapter DBDirect メソッドを使用してデータを保存する

その他の技術情報

Windows アプリケーションのフォームでのデータの表示

TableAdapter

データの保存