Share via


Procedura dettagliata: connessione ai dati negli oggetti (Windows Form)

Questa procedura dettagliata consente di creare oggetti per la gestione dei dati relativi a clienti e ordini, insieme a un'origine dati per ogni oggetto. L'origine dati oggetto viene visualizzata nella finestra Origini dati. Gli elementi vengono trascinati da tale finestra in un form in modo da creare controlli associati ai dati nelle proprietà pubbliche per ogni oggetto. Nella procedura dettagliata viene inoltre mostrato come utilizzare gli oggetti TableAdapter per recuperare i dati dal database e popolare gli oggetti.

L'origine dati oggetto viene creata eseguendo la Configurazione guidata origine dati e selezionando il tipo di origine dati Oggetto. Al termine della Configurazione guidata origine dati, le proprietà pubbliche dell'oggetto saranno disponibili nella Origini dati (finestra) e potranno essere trascinate nel form.

Di seguito vengono illustrate le attività incluse nella procedura dettagliata:

  • Creazione di un nuovo progetto Applicazione Windows Form.

  • Creazione di oggetti personalizzati che rappresentano clienti e ordini.

  • Creazione e configurazione di un'origine dati oggetto in base agli oggetti personalizzati mediante la Configurazione guidata origine dati.

  • Aggiunta a un form di controlli associati a dati di oggetti personalizzati.

  • Creazione di un dataset con oggetti TableAdapter per spostare i dati fra gli oggetti e il database.

  • Modifica della query principale di un oggetto TableAdapter.

  • Aggiunta di query a un oggetto TableAdapter.

  • Popolamento degli oggetti con i dati del database.

Creazione del progetto

Per creare il nuovo progetto Applicazione Windows Form

  1. Scegliere Nuovo progetto dal menu File.

  2. Fare clic su Windows nel riquadro Tipi progetto al di sotto del nodo per la lingua che si desidera utilizzare.

  3. Nel riquadro Modelli fare clic su Applicazione Windows Form.

  4. Nella casella Nome digitare ObjectBindingWalkthrough, quindi fare clic su OK.

    Il progetto ObjectBindingWalkthrough viene creato e aggiunto a Esplora soluzioni.

Per questa procedura dettagliata è necessario disporre di oggetti con cui effettuare l'associazione. Nel primo passaggio è prevista la creazione di alcuni oggetti di esempio che rappresentino clienti e ordini. Per rappresentare i clienti verrà creato un oggetto Customer che rappresenta un singolo cliente. Per rappresentare gli ordini verrà creato un oggetto Order che rappresenta un singolo ordine e un oggetto Orders che rappresenta una raccolta di oggetti Order. Per la raccolta di oggetti Customer verrà utilizzata la raccolta incorporata nella classe BindingSource, illustrata più avanti in questa procedura dettagliata.

Creazione dell'oggetto Customer

Per creare l'oggetto Customer

  1. Scegliere Aggiungi classe dal menu Progetto.

  2. Assegnare il nome Customer alla nuova classe e scegliere Aggiungi.

  3. Sostituire il codice nel file della classe Customer con il codice seguente:

    Nota

    L'oggetto Customer contiene una proprietà ordersCollection del tipo Orders.Nell'editor verrà visualizzato il messaggio Tipo 'Orders' non definito.Questo messaggio è previsto e non sarà più visualizzato quando nella sezione successiva verranno create le classi Order e Orders.

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

Creazione degli oggetti Order

Per creare l'oggetto Order e la raccolta Orders

  1. Scegliere Aggiungi classe dal menu Progetto.

  2. Assegnare il nome Order alla nuova classe e scegliere Aggiungi.

  3. Sostituire il codice nel file della classe Order con il codice seguente:

    ''' <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. Scegliere Salva tutto dal menu File.

Creazione dell'origine dati oggetto

È possibile creare un'origine dati in base agli oggetti creati nel passaggio precedente mediante l'esecuzione della Configurazione guidata origine dati.

Per creare l'origine dati oggetto

  1. Compilazione del progetto.

    Nota

    È necessario compilare il progetto per poter selezionare gli oggetti del progetto in Configurazione guidata origine dati.

  2. Aprire la finestra Origini dati facendo clic sul menu Dati e scegliendo Mostra origini dati.

  3. Scegliere Aggiungi nuova origine dati nella finestra Origini dati.

    Verrà avviata la Configurazione guidata origine dati.

  4. Nella pagina Seleziona un tipo di origine dati selezionare Oggetto, quindi fare clic su Avanti.

  5. Nella pagina Selezionare gli oggetti dati espandere i nodi ObjectBindingWalkthrough e selezionare la casella di controllo accanto all'oggetto Customer.

  6. Fare clic su Fine.

    Nella finestra Origini dati verrà visualizzato l'oggetto Customer.

Creazione di un form con associazione a dati

È possibile creare i controlli con associazione all'oggetto Customer trascinando degli elementi dalla finestra Origini dati a un form.

Per creare un Form con controlli associati alle proprietà dell'oggetto

  1. In Esplora soluzioni scegliere Form1, quindi fare clic su Progettazione visualizzazioni.

  2. Trascinare il nodo Cliente dalla finestra Origini dati in Form1.

  3. Espandere il nodo Cliente e trascinare il nodo Ordini dalla finestra Origini dati in Form1.

Creazione di oggetti TableAdapters per caricare dati dal database negli oggetti personalizzati

Per spostare i dati tra gli oggetti e il database, verranno utilizzati gli oggetti TableAdapter. È possibile creare oggetti TableAdapter per le tabelle Customers e Orders mediante la Configurazione guidata origine dati.

Per creare oggetti TableAdapter

  1. Scegliere Aggiungi nuova origine dati dal menu Dati.

  2. Nella pagina Seleziona un tipo di origine dati selezionare Database, quindi fare clic su Avanti.

  3. Nella pagina Scegli modello database selezionare DataSet e scegliere Avanti.

  4. Nella pagina Seleziona connessione dati seguire una delle procedure seguenti:

    • Selezionare la connessione dati al database di esempio Northwind nell'elenco a discesa, se presente.

      In alternativa

    • Selezionare Nuova connessione per configurare una nuova connessione dati al database Northwind. Per ulteriori informazioni, vedere Procedura: connettersi ai dati di un database.

  5. Dopo avere selezionato una connessione dati, fare clic su Avanti.

  6. Nella pagina Salva la stringa di connessione nel file di configurazione applicazione scegliere Avanti.

  7. Nella pagina Seleziona oggetti di database espandere il nodo Tabelle.

  8. Selezionare le tabelle Customers e Orders, quindi scegliere Fine.

    Il nodo NorthwindDataSet verrà aggiunto al progetto e le tabelle Customers e Orders verranno visualizzate nella finestra Origini dati sotto a NorthwindDataSet.

Aggiunta del dataset e di TableAdapter a Form1

È possibile aggiungere istanze dell'oggetto CustomersTableAdapter, OrdersTableAdapter e NorthwindDataSet al form trascinando i componenti che li rappresentano dalla Casella degli strumenti.

Per compilare gli oggetti Customer con dati contenuti nella tabella Customers

  1. Scegliere Compila soluzione dal menu Compila.

  2. Trascinare un oggetto NorthwindDataSet dalla Casella degli strumenti su Form1.

  3. Trascinare un oggetto CustomersTableAdapter dalla Casella degli strumenti su Form1.

  4. Trascinare un oggetto OrdersTableAdapter dalla Casella degli strumenti su Form1.

Aggiunta di una query all'oggetto CustomersTableAdapter per estrarre solo alcuni clienti

Nelle applicazioni reali con molta probabilità non sarà mai necessario restituire l'intera tabella di dati. In questa procedura dettagliata verranno estratti solo i primi cinque clienti.

Nota

Per selezionare i clienti che si desidera vengano restituiti, di norma si dovrebbe passare un parametro, ma per brevità in questa procedura dettagliata la query verrà impostata a livello di codice in modo che vengano restituiti soltanto cinque clienti, eliminando la necessità di creare un'interfaccia utente per l'immissione dei valori dei parametri.

Per aggiungere un'altra query all'oggetto CustomersTableAdapter

  1. In Esplora soluzioni, fare doppio clic sul file NorthwindDataSet.xsd.

    Il dataset NorthwindDataset viene aperto in Progettazione DataSet.

  2. Fare clic con il pulsante destro del mouse su CustomersTableAdapter e selezionare Aggiungi query.

    Verrà visualizzata la TableAdapter (query, configurazione guidata).

  3. Lasciare il valore predefinito Usa istruzioni SQL, quindi scegliere Avanti.

  4. Lasciare il valore predefinito SELECT che restituisce righe e scegliere Avanti.

  5. Sostituire l'istruzione SQL con quanto indicato di seguito e scegliere Avanti:

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. Deselezionare la casella di controllo Riempi un DataTable.

  7. Assegnare al metodo Riempi un DataTable il nome GetTop5Customers e scegliere Fine.

    La query GetTop5Customers verrà aggiunta all'oggetto CustomersTableAdapter.

Modifica della query relativa all'oggetto OrdersTableAdapter per estrarre solo gli ordini di un determinato cliente

Si supponga di dover recuperare gli ordini dal database senza voler estrarre l'intera tabella di ordini, bensì solo gli ordini di uno specifico cliente. Nella procedura seguente viene descritto in modo dettagliato come riconfigurare un oggetto TableAdapter con una nuova query anziché aggiungere un'altra query come è stato fatto nel passaggio precedente con l'oggetto CustomersTableAdapter.

Per riconfigurare la query principale del TableAdapter per recuperare gli ordini di un solo cliente

  1. Fare clic con il pulsante destro del mouse su OrdersTableAdapter, quindi scegliere Configura.

    Verrà visualizzata la TableAdapter (query, configurazione guidata).

  2. Sostituire l'istruzione SQL con quanto indicato di seguito e scegliere Avanti:

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. Deselezionare la casella di controllo Riempi un DataTable.

  4. Assegnare al metodo Riempi un DataTable il nome GetDataByCustomerID e scegliere Fine.

    La query principale Fill dell'oggetto OrdersTableAdapter viene sostituita dalla query GetDataByCustomerID.

  5. Compilare il progetto scegliendo Compila soluzione dal menu Compila.

Aggiunta di codice per caricare dati negli oggetti Customer e Order

Per caricare dati negli oggetti personalizzati, è necessario eseguire le query degli oggetti TableAdapter che restituiscono nuove tabelle di dati, anziché le query degli oggetti TableAdapter che consentono di compilare tabelle di dati esistenti. Con l'esecuzione del codice viene quindi effettuato lo scorrimento della tabella e ogni oggetto Customer viene popolato con le informazioni sul cliente e inoltre vengono popolati tutti gli ordini di ogni raccolta Customer.Orders. Si osservi come ogni oggetto Customer viene aggiunto alla raccolta interna dell'oggetto CustomerBindingSource (CustomerBindingSource.Add(currentCustomer)). BindingSource fornisce una raccolta fortemente tipizzata incorporata di oggetti Customers cui è possibile accedere tramite la proprietà List.

Per caricare gli oggetti con i dati

  1. In Esplora soluzioni selezionare Form1, quindi scegliere Visualizza codice.

  2. Sostituire il codice in Form1 con quello seguente:

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

Verifica dell'applicazione

Per eseguire il test dell'applicazione

  1. ‎Premere F5 per eseguire l'applicazione.

  2. Il form viene aperto e i controlli DataGridView vengono popolati con i dati di esempio.

  3. Spostarsi tra i clienti visualizzati nell'oggetto DataGridView per visualizzare gli ordini ad essi associati.

Passaggi successivi

Per aggiungere funzionalità all'applicazione

Vedere anche

Concetti

Preparazione dell'applicazione al ricevimento di dati

Recupero di dati nell'applicazione

Associazione di controlli ai dati in Visual Studio

Modifica di dati nell'applicazione

Associazione di oggetti in Visual Studio

Salvataggio di dati

Altre risorse

Connessione ai dati in Visual Studio

Procedure dettagliate relative ai dati