다음을 통해 공유


연습: 개체의 데이터에 연결

업데이트: 2007년 11월

이 연습에서는 개체를 만들어 고객 및 주문 데이터를 보관하고 이러한 개체를 기반으로 개체 데이터 소스를 만드는 방법을 보여 줍니다. 개체 데이터 소스가 데이터 소스 창에 나타나고 이 창에서 항목을 폼으로 끌어 와 해당 개체의 공용 속성에 있는 데이터에 바인딩된 컨트롤을 만듭니다. 또한 이 연습에서는 TableAdapter를 사용하여 데이터베이스에서 데이터를 페치하고 개체를 채우는 방법도 보여 줍니다.

개체 데이터 소스는 데이터 소스 구성 마법사를 실행하고 데이터 소스의 형식으로 개체를 선택하여 만듭니다. 데이터 소스 구성 마법사를 완료하면 개체의 공용 속성을 데이터 소스 창에서 폼으로 끌어서 놓을 수 있게 됩니다.

참고:

개체가 데이터 소스 구성 마법사에 나타나려면 그 개체가 포함된 프로젝트를 빌드해야 합니다. 마법사에서 원하는 개체를 사용할 수 없는 경우 그 개체가 포함된 프로젝트를 다시 빌드하십시오.

이 연습에서 수행할 작업은 다음과 같습니다.

  • 새 Windows 응용 프로그램 프로젝트를 만듭니다.

  • 고객 및 주문을 나타내는 샘플 개체를 만듭니다.

  • 데이터 소스 구성 마법사를 사용하여 샘플 개체를 기반으로 응용 프로그램에서 개체 데이터 소스를 만들고 구성합니다.

  • 사용자 지정 개체의 데이터에 바인딩되어 있는 컨트롤을 폼에 추가합니다.

  • TableAdapter를 사용하여 데이터 집합을 만들어 개체와 데이터베이스 간에 데이터를 이동합니다.

  • TableAdapter의 주 쿼리를 편집합니다.

  • TableAdapter에 쿼리를 추가합니다.

  • 데이터베이스의 데이터로 개체를 채웁니다.

프로젝트 만들기

새 Windows 응용 프로그램 프로젝트를 만들려면

  1. 파일 메뉴에서 새 프로젝트를 만듭니다.

  2. 이름이 ObjectBindingWalkthrough인 Windows 응용 프로그램을 만들고 확인을 클릭합니다. 자세한 내용은 Windows 기반 응용 프로그램 만들기를 참조하십시오.

    ObjectBindingWalkthrough 프로젝트가 만들어져 솔루션 탐색기에 추가됩니다.

이 연습에는 바인딩할 개체가 필요하므로 먼저 고객과 주문을 나타내는 샘플 개체를 몇 개 만듭니다. 고객을 나타내기 위해 단일 고객을 나타내는 Customer 개체를 만듭니다. 주문을 나타내기 위해 단일 주문을 나타내는 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 Integer, _
                       ByVal orderDate As DateTime, _
                       ByVal requiredDate As DateTime, _
                       ByVal shippedDate As DateTime, _
                       ByVal shipVia As Integer, _
                       ByVal freight As 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 Integer
        ''' <summary>
        ''' The ID of the employee who took this order
        ''' </summary>
        Public Property EmployeeID() As Integer
            Get
                Return employeeIDValue
            End Get
            Set(ByVal Value As Integer)
                employeeIDValue = Value
            End Set
        End Property
    
    
        Private orderDateValue As DateTime
        ''' <summary>
        ''' The date this order was placed
        ''' </summary>
        Public Property OrderDate() As DateTime
            Get
                Return orderDateValue
            End Get
            Set(ByVal Value As DateTime)
                orderDateValue = Value
            End Set
        End Property
    
        Private requiredDateValue As DateTime
        ''' <summary>
        ''' The date this order is required
        ''' </summary>
        Public Property RequiredDate() As DateTime
            Get
                Return requiredDateValue
            End Get
            Set(ByVal Value As DateTime)
                requiredDateValue = Value
            End Set
        End Property
    
    
        Private shippedDateValue As DateTime
        ''' <summary>
        ''' The date this order was shipped
        ''' </summary>
        Public Property ShippedDate() As DateTime
            Get
                Return shippedDateValue
            End Get
            Set(ByVal Value As DateTime)
                shippedDateValue = Value
            End Set
        End Property
    
        Private shipViaValue As Integer
        ''' <summary>
        ''' The shipping method for this order
        ''' </summary>
        Public Property ShipVia() As Integer
            Get
                Return shipViaValue
            End Get
            Set(ByVal Value As Integer)
                shipViaValue = Value
            End Set
        End Property
    
    
        Private freightValue As Decimal
        ''' <summary>
        ''' The freight charge for this order
        ''' </summary>
        Public Property Freight() As Decimal
            Get
                Return freightValue
            End Get
            Set(ByVal Value As 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,
             int employeeID, DateTime orderDate,
             DateTime requiredDate, DateTime shippedDate,
             int shipVia, 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 int employeeIDValue;
          /// <summary>
          /// The ID of the employee who took this order
          /// </summary>
          public int EmployeeID
          {
             get { return employeeIDValue; }
             set { employeeIDValue = value; }
          }
    
          private DateTime orderDateValue;
          /// <summary>
          /// The date this order was placed
          /// </summary>
          public DateTime OrderDate
          {
             get { return orderDateValue; }
             set { orderDateValue = value; }
          }
    
          private DateTime requiredDateValue;
          /// <summary>
          /// The date this order is required
          /// </summary>
          public DateTime RequiredDate
          {
             get { return requiredDateValue; }
             set { requiredDateValue = value; }
          }
    
          private DateTime shippedDateValue;
          /// <summary>
          /// The date this order was shipped
          /// </summary>
          public DateTime ShippedDate
          {
             get { return shippedDateValue; }
             set { shippedDateValue = value; }
          }
    
          private int shipViaValue;
          /// <summary>
          /// The shipping method of this order
          /// </summary>
          public int ShipVia
          {
             get { return shipViaValue; }
             set { shipViaValue = value; }
          }
    
          private decimal freightValue;
          /// <summary>
          /// The freight charge for this order
          /// </summary>
          public 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. ObjectBindingWalkthrough 노드를 확장하고 Customer 개체를 선택합니다.

    참고:

    Customer 개체를 사용할 수 없으면 취소를 클릭한 다음 빌드 메뉴에서 ObjectBindingWalkthrough 빌드를 선택합니다. 프로젝트를 성공적으로 빌드한 다음 마법사를 다시 시작하면(2단계) 사용자 지정 개체가 나타납니다.

  5. 마침을 클릭합니다.

    데이터 소스 창에 Customer 개체가 나타납니다.

데이터 바인딩된 폼 만들기

데이터 소스 창에서 폼으로 항목을 끌어 와 Customer 개체에 바인딩된 컨트롤을 만들 수 있습니다.

개체 속성에 바인딩된 컨트롤이 있는 폼을 만들려면

  1. 솔루션 탐색기에서 Form1을 선택하고 디자이너 보기를 클릭합니다.

  2. Customer 노드를 데이터 소스 창에서 Form1로 끌어서 놓습니다.

  3. Customer 노드를 확장하고 Orders 노드를 데이터 소스 창에서 Form1로 끌어서 놓습니다.

데이터를 데이터베이스에서 사용자 지정 개체로 로드하도록 TableAdapter 만들기

개체와 데이터베이스 간에 데이터를 이동하려면 TableAdapter를 사용합니다. 데이터 소스 구성 마법사를 사용하여 Customers 및 Orders 테이블에 대한 TableAdapter를 만들 수 있습니다.

TableAdapter를 만들려면

  1. 데이터 메뉴에서 새 데이터 소스 추가를 선택합니다.

  2. 데이터 소스 형식 선택 페이지에서 데이터베이스를 선택합니다.

  3. 데이터 연결 선택 페이지에서 다음 중 한 가지를 수행합니다.

  4. 응용 프로그램 구성 파일에 연결 문자열 저장 페이지에서 다음을 클릭합니다.

  5. 데이터베이스 개체 선택 페이지에서 테이블 노드를 확장합니다.

  6. Customers 및 Orders 테이블을 선택한 다음 마침을 클릭합니다.

    NorthwindDataSet이 프로젝트에 추가되고 Customers 및 Orders 테이블이 NorthwindDataSet 노드 아래의 데이터 소스 창에 나타납니다.

Form1에 데이터 집합 및 TableAdapter 추가

도구 상자에서 표현 구성 요소를 끌어 와 CustomersTableAdapter, OrdersTableAdapter 및 NorthwindDataSet의 인스턴스를 폼에 추가할 수 있습니다.

Customers 테이블의 데이터로 Customer 개체를 채우려면

  1. 빌드 메뉴에서 솔루션 빌드를 선택합니다.

  2. NorthwindDataSet을 도구 상자에서 Form1로 끌어서 놓습니다.

  3. CustomersTableAdapter를 도구 상자에서 Form1로 끌어서 놓습니다.

  4. OrdersTableAdapter를 도구 상자에서 Form1로 끌어서 놓습니다.

일부 고객만 반환하도록 CustomersTableAdapter에 쿼리 추가

실제 응용 프로그램에서 전체 데이터 테이블을 반환하는 경우는 거의 없습니다. 이 연습에서는 상위 다섯 개의 고객을 반환합니다.

참고:

일반적으로 매개 변수를 전달하여 반환하려는 고객을 선택합니다. 그러나 이 연습에서는 간단히 나타내기 위해 쿼리를 하드 코딩하여 다섯 개의 고객만 반환하고 매개 변수 값을 입력하는 사용자 인터페이스를 만들지 않기로 합니다.

CustomersTableAdapter에 추가 쿼리를 추가하려면

  1. 솔루션 탐색기에서 NorthwindDataSet.xsd 파일을 두 번 클릭합니다.

    데이터 집합 디자이너에서 NorthwindDataSet을 엽니다.

  2. CustomersTableAdapter를 마우스 오른쪽 단추로 클릭하고 Query 추가를 선택합니다.

    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에 새로 쿼리를 추가한 것과 대조되는 방식입니다.

단일 고객의 주문을 반환하도록 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에서 데이터에 연결

데이터를 받기 위해 응용 프로그램 준비

데이터를 응용 프로그램으로 페치

Windows 응용 프로그램에서 폼에 데이터 표시

응용 프로그램에서 데이터 편집

데이터 저장

데이터 연습