Tutorial: Conectar a los datos en objetos (Windows Forms)

En este tutorial se crean objetos para conservar datos de pedidos y clientes, junto con un origen de datos de objeto para cada objeto. El origen de datos de objeto aparece en la ventana Orígenes de datos, desde la que se arrastran elementos hasta los formularios para crear controles enlazados a los datos de las propiedades públicas de cada objeto. En el tutorial también se muestra cómo utilizar TableAdapters para tomar los datos de la base de datos y rellenar los objetos.

El origen de datos de objeto se crea ejecutando el Asistente para la configuración de orígenes de datos y seleccionando Objeto como el tipo de origen de datos. Después de completar el Asistente para la configuración de orígenes de datos, las propiedades públicas del objeto están disponibles en la Orígenes de datos (ventana) y pueden arrastrarse al formulario.

Las tareas que se ilustran en este tutorial son las siguientes:

  • Crear un proyecto nuevo de aplicación de Windows Forms.

  • Crear objetos personalizados para representar clientes y pedidos.

  • Crear y configurar un origen de datos de objeto basado en los objetos personalizados utilizando el Asistente para la configuración de orígenes de datos.

  • Agregar a un formulario controles que están enlazados a los datos de los objetos personalizados.

  • Crear un conjunto de datos con TableAdapters para mover datos entre los objetos y la base de datos.

  • Modificar la consulta principal de un TableAdapter.

  • Agregar consultas a un TableAdapter.

  • Rellenar los objetos con datos de la base de datos.

Crear el proyecto

Para crear el nuevo proyecto de aplicación Windows Forms

  1. En el menú Archivo, cree un Nuevo proyecto.

  2. En el recuadro Tipos de proyecto, bajo el nodo del lenguaje que desee utilizar, haga clic en Windows.

  3. En el panel Plantillas, haga clic en Aplicación de Windows Forms.

  4. En el cuadro Nombre, escriba ObjectBindingWalkthrough y haga clic en Aceptar.

    Se crea el proyecto ObjectBindingWalkthrough y se agrega al Explorador de soluciones.

En este tutorial se necesitan algunos objetos a los que enlazar. El primer paso es crear objetos de ejemplo para representar clientes y pedidos. Para representar los clientes, crearemos un objeto Customer que representa un único cliente. Para representar los pedidos, crearemos un objeto Order que representa un único pedido y un objeto Orders que representa una colección de objetos Order. Para la colección de los objetos Customer, utilizaremos la colección integrada en la clase BindingSource (explicada más adelante en este tutorial).

Crear el objeto Customer

Para crear el objeto Customer

  1. En el menú Proyecto, haga clic en Agregar clase.

  2. Asigne a la nueva clase el nombre Customer y haga clic en Agregar.

  3. Reemplace el código del archivo de clase Customer por el código siguiente:

    Nota

    El objeto Customer contiene una propiedad ordersCollection del tipo Orders. El editor muestra un mensaje que indica El tipo 'Orders' no está definido. Este mensaje es normal y desaparecerá cuando cree las clases Order y Orders en la sección siguiente.

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

Crear los objetos Order

Para crear el objeto Order y la colección Orders

  1. En el menú Proyecto, elija Agregar clase.

  2. Asigne a la nueva clase el nombre Order y haga clic en Agregar.

  3. Reemplace el código del archivo de clase Order con el código siguiente:

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

Crear el origen de datos de objeto

Puede crear un origen de datos basado en los objetos creados en el paso anterior ejecutando el Asistente para la configuración de orígenes de datos.

Para crear el origen de datos de objeto

  1. Generar el proyecto.

    Nota

    Debe compilar el proyecto para que los objetos del proyecto se puedan seleccionar en el Asistente para la configuración de orígenes de datos.

  2. Abra la ventana Orígenes de datos haciendo clic en el menú Datos y seleccionando Mostrar orígenes de datos.

  3. Haga clic en Agregar nuevo origen de datos en la ventana Orígenes de datos.

    Se inicia el Asistente para la configuración de orígenes de datos.

  4. En la página Elegir un tipo de origen de datos, seleccione Objeto y luego en Siguiente.

  5. En la página Seleccionar los objetos de datos, expanda los nodos ObjectBindingWalkthrough y active la casilla situada junto al objeto Customer.

  6. Haga clic en Finalizar.

    El objeto Customer aparece en la ventana Orígenes de datos.

Crear un formulario enlazado a datos

Los controles enlazados al objeto Customer se crean arrastrando elementos desde la ventana Orígenes de datos hasta un formulario.

Para crear un formulario con controles enlazados a las propiedades del objeto

  1. En el Explorador de soluciones, seleccione Form1 y haga clic en el Diseñador de vistas.

  2. Desde la ventana Orígenes de datos, arrastre el nodo Customer hasta Form1.

  3. Expanda el nodo Customer y arrastre el nodo Orders desde la ventana Orígenes de datos hasta Form1.

Crear TableAdapters para cargar datos de la base de datos en los objetos personalizados

Para mover datos entre los objetos y la base de datos, vamos a utilizar TableAdapters. Puede crear TableAdapters para las tablas Customers y Orders utilizando el Asistente para la configuración de orígenes de datos.

Para crear los TableAdapters

  1. En el menú Datos, elija Agregar nuevo origen de datos.

  2. En la página Elegir un tipo de origen de datos, seleccione Base de datos y, a continuación, haga clic en Siguiente.

  3. En la página Elegir un modelo de base de datos, seleccione Conjunto de datos y, a continuación, haga clic en Siguiente.

  4. En la página Elegir la conexión de datos, realice uno de estos procedimientos:

    • Si una conexión de datos a la base de datos de ejemplo Northwind está disponible en la lista desplegable, selecciónela.

      O bien

    • Seleccione Nueva conexión para configurar una nueva conexión de datos a la base de datos Northwind. Para obtener más información, vea Cómo: Conectarse a los datos de una base de datos.

  5. Después de seleccionar una conexión de datos, haga clic en Siguiente.

  6. Haga clic en Siguiente en la página Guardar la cadena de conexión en el archivo de configuración de la aplicación.

  7. Expanda el nodo Tablas en la página Elija los objetos de base de datos.

  8. Seleccione las tablas Customers y Orders y, a continuación, haga clic en Finalizar.

    Se agrega al proyecto el conjunto de datos NorthwindDataSet y las tablas Customers y Orders aparecen en la ventana Orígenes de datos, bajo el nodo NorthwindDataSet.

Agregar el conjunto de datos y los adaptadores de tabla a Form1

Puede agregar instancias de CustomersTableAdapter, OrdersTableAdapter y NorthwindDataSet al formulario arrastrando sus componentes representativos desde el Cuadro de herramientas.

Para rellenar los objetos Customer con datos de la tabla Customers

  1. En el menú Generar, seleccione Generar solución.

  2. Arrastre un conjunto de datos NorthwindDataSet desde el Cuadro de herramientas hasta Form1.

  3. Arrastre un adaptador CustomersTableAdapter desde el Cuadro de herramientas hasta Form1.

  4. Arrastre un adaptador OrdersTableAdapter desde el Cuadro de herramientas hasta Form1.

Agregar una consulta al adaptador CustomersTableAdapter para que sólo devuelva algunos clientes

En aplicaciones reales, probablemente nunca devolverá la tabla completa de datos. Para este tutorial, devolveremos los cinco primeros clientes.

Nota

Normalmente pasaría un parámetro para seleccionar qué clientes desea devolver, pero por cuestiones de brevedad en este tutorial, incluiremos directamente el código de la consulta para que sólo devuelva cinco clientes y eliminar la necesidad de crear una interfaz de usuario donde especificar los valores de los parámetros.

Para agregar una consulta adicional al adaptador CustomersTableAdapter

  1. En el Explorador de soluciones, haga doble clic en el archivo NorthwindDataSet.xsd.

    Se abre el conjunto de datos NorthwindDataSet en el Diseñador de Dataset.

  2. Haga clic con el botón secundario del mouse en CustomersTableAdapter y seleccione Agregar consulta.

    Se abrirá el Asistente para la configuración de consultas de TableAdapter.

  3. Deje la opción predeterminada de Usar instrucciones SQL y, a continuación, haga clic en Siguiente.

  4. Deje la opción predeterminada de SELECT que devuelve filas y haga clic en Siguiente.

  5. Reemplace la instrucción SQL con la siguiente y haga clic en Siguiente:

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. Desactive la casilla Rellenar un DataTable.

  7. Asigne al método Devolver un DataTable el nombre GetTop5Customers y haga clic en Finalizar.

    La consulta GetTop5Customers se agrega al adaptador CustomersTableAdapter.

Modificar la consulta del adaptador OrdersTableAdapter para que sólo devuelva los pedidos del cliente deseado

Al recuperar pedidos de la base de datos, no deseamos que se devuelva la tabla completa de pedidos, sino sólo los correspondientes a un cliente específico. El procedimiento siguiente detalla cómo reconfigurar un adaptador TableAdapter con una nueva consulta (a diferencia de agregar una consulta adicional como hicimos con el adaptador CustomersTableAdapter en el paso anterior).

Para reconfigurar la consulta principal del TableAdapter para que devuelva los pedidos de un único cliente

  1. Haga clic con el botón secundario del mouse en OrdersTableAdapter y elija Configurar.

    Se abrirá el Asistente para la configuración de consultas de TableAdapter.

  2. Reemplace la instrucción SQL con la siguiente y haga clic en Siguiente:

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. Desactive la casilla Rellenar un DataTable.

  4. Asigne al método Devolver un DataTable el nombre GetDataByCustomerID y haga clic en Finalizar.

    La consulta Fill principal del adaptador OrdersTableAdapter se reemplaza con la consulta GetDataByCustomerID.

  5. Compile el proyecto seleccionando Generar solución en el menú Generar.

Agregar código para cargar datos en los objetos Customer y Order

Para cargar datos en los objetos personalizados, ejecute las consultas de TableAdapter que devuelven nuevas tablas de datos (en lugar que usar las consultas del TableAdapter que rellenan tablas de datos existentes). A continuación, el código recorre la tabla y va rellenando cada objeto Customer con la información del cliente, así como todos los pedidos de cada colección Customer.Orders. Observe cómo cada objeto Customer se agrega a la colección interna de CustomerBindingSource (CustomerBindingSource.Add(currentCustomer)). BindingSource proporciona una colección fuertemente tipada e integrada de Customers al que se puede tener acceso a través de la propiedad List.

Para cargar datos en los objetos

  1. En el Explorador de soluciones, seleccione Form1 y haga clic en Ver código.

  2. Reemplace el código de Form1 por el siguiente 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();
            }
    
        }
    }
    

Probar la aplicación

Para probar la aplicación

  1. Presione F5 para ejecutar la aplicación.

  2. Se abre el formulario y se rellenan los controles DataGridView con los datos de ejemplo.

  3. Navegue por los clientes contenidos en el control DataGridView que muestran los pedidos que tienen asociados.

Pasos siguientes

Para agregar funcionalidad a la aplicación

Vea también

Conceptos

Enlazar controles a los datos en Visual Studio

Enlace de objetos en Visual Studio

Otros recursos

Conectarse a datos en Visual Studio

Preparar la aplicación para recibir datos

Buscar datos en la aplicación

Modificar datos en la aplicación

Guardar datos

Tutoriales sobre datos