Demonstra Passo a passo: Conectando-se a dados in Objects

Esta explicação passo a passo mostra como criar objetos para manter cliente e dados de pedidos e cria um objeto de fonte de dados com base nesses objetos.O objeto de fonte de dados aparece na janela Data Sources onde os itens são arrastados em um formulário para criar controles acoplados a dados nas propriedades públicas do objeto.A explicação passo a passo também mostra como usar TableAdapters para buscar dados a partir do banco de dados e preencher os objetos.

A fonte de dados de objeto é criada executando o Assistente de Configuração de Fonte de Dados e selecionando Object como o tipo da fonte de dados.Após concluído o Data Source Configuration Wizard, as propriedades públicas do objeto estão disponíveis no Janela Fontes de Dados para serem arrastadas para seu formulário.

Observação:

Você precisa construir o projeto que contém o objeto para que ele apareça na Assistente para configuração da fonte de dados.Se o objeto não estiver disponível para o assistente, recrie o projeto que contém o(s) objeto(s) desejado(s).

Tarefas ilustradas nesta explicação passo a passo incluem:

  • Criando um novo projeto Windows Application.

  • Criando objetos de exemplo para representar os Clientes e Pedidos.

  • Criar e configurar um objeto de fonte de dados em seu aplicativo baseado em objeto exemplo usando o Data Source Configuration Wizard.

  • Adicionar controles a um formulário que está acoplado para os dados em objetos personalizados.

  • Criando um DataSet com TableAdapter para mover dados entre os objetos e o banco de dados.

  • Editando um TableAdapter da consulta principal.

  • Adicionando consultas a um TableAdapter.

  • Preenchendo os objetos com dados de banco de dados.

Criando o projeto

Para criar o novo projeto do Windows Application

  1. No menu File crie um New Project.

  2. Crie um Windows Application chamado ObjectBindingWalkthrough e clique em OK.Para obter mais informações, consulte Criando Aplicativos Baseados no Windows.

    O projeto ObjectBindingWalkthrough é criado e adicionado Solution Explorer.

Esta explicação passo a passo precisa de alguns objetos para vincular, portanto a primeira etapa é criar alguns objetos de exemplo para representar os Clientes e Pedidos.Para representar clientes nós criaremos um objeto Customer que representa um único cliente.Para representar pedidos nós criaremos um objeto Order que representa uma ordem única e um objeto Orders que representa uma coleção de objetos Order.Para a coleção de objetos Customer usaremos a coleção interna na classe BindingSource (explicada posteriormente nessa explicação passo a passo).

Criando o objeto cliente

Para criar o objeto cliente

  1. No menu Project clique em Add Class.

  2. Nomeie a nova classe Customer e clique em Add.

  3. Substitua o código no arquivo da classe Customer com o seguinte código:

    Observação:

    O Customer objeto contém uma ordersCollection propriedade do tipo Orders. O editor exibirá uma mensagem informando Type 'Orders' is not defined.Esta mensagem é esperada e desaparecerá quando você criar as classes Order e Orders na próxima seção.

    ''' <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 + ")";
            }
        }
    }
    

Criando os objetos Orders

Para criar o objeto Order e a coleção de pedidos (Orders)

  1. No menu Project selecione Add Class.

  2. Nomeie a nova classe como Order e clique em Add.

  3. Substitua o código no arquivo da classe Order com o seguinte código:

    ''' <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. No menu File escolha Save All.

Criar o objeto de fonte de dados

Você pode criar uma fonte de dados com base nos objetos criados na etapa anterior, executando o Data Source Configuration Wizard.

Para criar o objeto de fonte de dados

  1. Abra a janela Data Sources clicando no menu Data e escolha Show Data Sources.

  2. Clique Add New Data Source na janela Data Sources.

  3. Selecione Object na página Choose a Data Source Type e clique em Next.

  4. Expanda os nós ObjectBindingWalkthrough e selecione o objeto Customer.

    Observação:

    Se a Cliente objeto não estiver disponível, clicar Cancelare, em seguida, selecionar Build ObjectBindingWalkthrough from the Compilação menu.Após criar o projeto com êxito, reinicie o assistente (etapa 2) e os objetos personalizados serão exibidos.

  5. Clique em Finish.

    O objeto Customer aparece na janela Data Sources.

Criar um formulário acoplado a dados

Controles limite à Customer objeto são criados arrastando itens a partir do Fontes de dados janela em um formulário.

Para criar um formulário com controles acoplados às propriedades do objeto

  1. No Solution Explorer, selecione Form1 e clique em View Designer.

  2. Arraste o nó Customer da janela Data Sources em Form1.

  3. Expanda o nó Customer nó e arraste o nó Orders do Data Sources w indow em Form1.

Criando TableAdapters para carregar dados de banco de dados para os objetos personalizados

Para mover dados entre os objetos e o banco de dados, nós iremos usar TableAdapters.Você pode criar TableAdapters para as tabelas Clientes e Pedidos usando o Assistente de Configuração de Fonte de Dados.

Para criar o TableAdapters

  1. No menu Data, escolha Add New Data Source.

  2. Selecione Database na página Choose a Data Source Type.

  3. Na página Choose your Data Connection, siga um destes procedimentos:

  4. Clique Next na página Save connection string to the Application Configuration file.

  5. Expanda o nó Tables na página Choose your Database Objects.

  6. Selecione as tabelas Customers e Orders, e clique Finish.

    O NorthwindDataSet é adicionado ao seu projeto e as tabelas Customers e Orders aparecem na janela Data Sources sob o nó NorthwindDataSet.

Adicionar o DataSet e TableAdapters para Form1

Você pode adicionar instâncias de CustomersTableAdapter,OrdersTableAdapter e NorthwindDataSet para o formulário arrastando seus componentes representativos da Toolbox.

Para preencher o objeto cliente (Customer) com dados da tabela Clientes

  1. No menu Build, escolha Build Solution.

  2. Arraste um NorthwindDataSet de Toolbox para Form1.

  3. Arraste um CustomersTableAdapter de Toolbox para Form1.

  4. Arraste um OrdersTableAdapter de Toolbox para Form1.

Adicionar uma consulta ao CustomersTableAdapter para retornar somente poucos clientes

Em aplicativos do mundo real, você provavelmente nunca retornará uma tabela inteira de dados.Para esta explicação passo a passo nós retornaremos os cinco clientes superiores.

Observação:

Você normalmente deve passar um parâmetro para selecionar quais clientes você deseja retornar, mas para abreviar esta explicação passo a passo nós codificaremos a consulta para retornar apenas cinco clientes e eliminar a necessidade de criar uma interface do usuário para entrar com valores de parâmetro.

Para adicionar uma consulta adicional para o CustomersTableAdapter

  1. No Solution Explorer, clique duas vezes no arquivo NorthwindDataSet.xsd.

    O NorthwindDataSet abre no Dataset Designer.

  2. Clique com o botão direito do mouse no CustomersTableAdapter e selecione Add Query.

    The Assistente de configuração da consulta TableAdapter opens.

  3. Deixe o padrão do Use SQL statements e clique em Next.

  4. Deixe o padrão de SELECT which returns rows e clique em Next.

  5. Substituir a instrução SQL pela seguinte e clique em Next:

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. Desmarque a caixa de seleção Fill a DataTable.

  7. Nomeie o Return a DataTable Método GetTop5Customers e clique em Finish.

    A consulta GetTop5Customers é adicionada ao CustomersTableAdapter.

Modificando a consulta no OrdersTableAdapter para retornar somente pedidos para o cliente desejado

Quando buscar pedidos do banco de dados, nós não desejamos retornar a tabela inteira de pedidos; apenas desejamos os pedidos para um cliente específico.O procedimento a seguir detalha como reconfigurar uma TableAdapter com uma nova consulta (em oposição a adicionar uma consulta adicional como nós fizemos para CustomersTableAdapter na etapa anterior).

Para reconfigurar o TableAdapter da consulta principal para retornar um único pedido de cliente.

  1. Clique com o botão direito do mouse no OrdersTableAdapter e escolha Configure.

    The Assistente de configuração da consulta TableAdapter opens.

  2. Substituir a instrução SQL pela seguinte e clique em Next:

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. Desmarque a caixa de seleção Fill a DataTable.

  4. Nomeie o Return a DataTable Método GetDataByCustomerID e clique em Finish.

    A consulta Fill principal do OrdersTableAdapter é substituída pela consulta GetDataByCustomerID.

  5. Criar o projeto escolhendo Build Solution no menu Build.

Adicionar código para carregar dados para os objetos cliente e pedido

Para carregar dados em nossos objetos personalizados, você executa as consultas do TableAdapter que retornam novas tabelas de dados (em oposição a consultas do TableAdapter que preenchem as tabelas de dados existente).O código então percorre a tabela e preenche cada objeto Customer com as informações do cliente, bem como preenche todos os pedidos em cada coleção Customer.Orders.Observe como cada objeto Customer é adicionado à coleção interna de CustomerBindingSource(CustomerBindingSource.Add(currentCustomer)); ou seja, o BindingSource fornece uma coleção interna fortemente tipada Customers acessível através da propriedade List.

Para carregar os objetos com dados

  1. No Solution Explorer selecione Form1 e clique em View Code.

  2. Substituir o código em Form1 com o seguinte código:

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

Testando o aplicativo

Para testar o aplicativo

  1. Pressione F5 para executar o aplicativo.

  2. O formulário abre e os controles DataGridView são preenchidos com os dados de exemplo.

  3. Navegue os clientes em DataGridView para exibir seus pedidos associados.

Próximas etapas

Para adicionar funcionalidade a seu aplicativo

Consulte também

Conceitos

Vinculação de objeto no Visual Studio

Outros recursos

Conectando-se a Dados no Visual Studio

Preparando seu aplicativo para receber dados

Buscando dados em seu aplicativo

Exibindo dados em formulários em aplicativos do Windows

Editar dados no seu aplicativo

Salvando dados

Explicações Passo a passo sobre Dados