演练:连接到对象中的数据(Windows 窗体)

本演练创建对象来存放客户和订单数据,并为每个对象创建一个对象数据源。 对象数据源显示在**“数据源”**窗口中:将从该窗口将项拖到窗体上,以创建绑定到每个对象的公共属性中的数据的控件。 本演练还演示如何使用 TableAdapter 从数据库获取数据并填充对象。

对象数据源是通过运行 数据源配置向导 并选择**“对象”作为数据源的类型创建的。 完成“数据源配置向导”**后,“数据源”窗口将提供对象的公共属性,并且可将这些属性拖到窗体上。

本演练涉及以下任务:

  • 创建新的**“Windows 窗体应用程序”**项目。

  • 创建表示客户和订单的自定义对象。

  • 使用**“数据源配置向导”**创建和配置基于自定义对象的对象数据源。

  • 向窗体添加绑定到自定义对象中的数据的控件。

  • 用 TableAdapter 创建数据集,以在对象与数据库之间移动数据。

  • 编辑 TableAdapter 的主查询。

  • 向 TableAdapter 添加查询。

  • 用来自数据库的数据填充对象。

创建项目

创建新的 Windows 窗体应用程序项目

  1. 从**“文件”菜单中创建一个“新项目”**。

  2. 在**“项目类型”窗格中您希望使用的语言节点下,单击“Windows”**。

  3. 在**“模板”窗格中,单击“Windows 窗体应用程序”**。

  4. 在**“名称”框中,键入 ObjectBindingWalkthrough,并单击“确定”**。

    **“ObjectBindingWalkthrough”项目即被创建并添加到“解决方案资源管理器”**中。

本演练需要一些作为绑定目标的对象。 第一步是创建一些表示客户和订单的示例对象。 为表示客户,我们将创建一个表示单个客户的 Customer 对象。 为表示订单,我们将创建一个表示单个订单的 Order 对象,以及一个表示 Order 对象集合的 Orders 对象。 对于 Customer 对象集合,我们将使用 BindingSource 类中的内置集合(在本演练后面部分进行说明)。

创建 Customer 对象

创建 Customer 对象

  1. 在**“项目”菜单上,单击“添加类”**。

  2. 将新类命名为 Customer,然后单击**“添加”**。

  3. 使用以下代码替换 Customer 类文件中的代码:

    备注

    Customer 对象包含类型 Orders 的 ordersCollection 属性。编辑器将显示消息“未定义类型‘Orders’”。出现此消息在意料之中,当您在下一节中创建 Order 和 Orders 类后它便会消失。

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

创建 Order 对象

创建 Order 对象和 Orders 集合

  1. 在**“项目”菜单上选择“添加类”**。

  2. 将新类命名为 Order,然后单击**“添加”**。

  3. 使用以下代码替换 Order 类文件中的代码:

    ''' <summary>
    ''' A single order
    ''' </summary>
    Public Class Order
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new order
        ''' </summary>
        ''' <param name="orderid">The identifier for this order</param>
        ''' <param name="customerID">The customer who placed this order</param>
        ''' <param name="employeeID">The ID of the employee who took this order</param>
        ''' <param name="orderDate">The date this order was placed</param>
        ''' <param name="requiredDate">The date this order is required</param>
        ''' <param name="shippedDate">The date the order was shipped</param>
        ''' <param name="shipVia">The shipping method for this order</param>
        ''' <param name="freight">The freight charge for this order</param>
        ''' <param name="shipName">The name of the recipient for this order</param>
        ''' <param name="shipAddress">The address to ship this order to</param>
        ''' <param name="shipCity">The city to ship this order to</param>
        ''' <param name="shipRegion">The region to ship this order to</param>
        ''' <param name="shipPostalCode">The postal code to ship this order to</param>
        ''' <param name="shipCountry">The country to ship this order to</param>
        Public Sub New(ByVal orderid As Integer,
                       ByVal customerID As String,
                       ByVal employeeID As 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. 在**“文件”菜单中选择“全部保存”**。

创建对象数据源

运行**“数据源配置向导”**,根据上一步中创建的对象可以创建数据源。

创建对象数据源

  1. 生成您的项目。

    备注

    您必须生成项目,然后才能在“数据源配置向导”中选择项目中的对象。

  2. 通过单击**“数据”菜单并选择“显示数据源”,打开“数据源”**窗口。

  3. 在**“数据源”窗口中单击“添加新数据源”**。

    将启动**“数据源配置向导”**。

  4. 在**“选择数据源类型”页上,选择“对象”,然后单击“下一步”**。

  5. 在**“选择数据对象”页上,展开“ObjectBindingWalkthrough”节点,并选中“Customer”**对象旁边的复选框。

  6. 单击**“完成”**。

    **“Customer”对象显示在“数据源”**窗口中。

创建数据绑定窗体

绑定到 Customer 对象的控件是通过将项从**“数据源”**窗口拖动到窗体上创建的。

创建其控件绑定到对象属性的窗体

  1. 在**“解决方案资源管理器”中,选择“Form1”,然后单击“视图设计器”**。

  2. 将**“Customer”节点从“数据源”窗口拖到“Form1”**上。

  3. 展开**“Customer”节点,并将“Orders”节点从“数据源”窗口拖到“Form1”**上。

创建 TableAdapter 以将数据从数据库加载到自定义对象中

为了在对象与数据库之间移动数据,我们将使用 TableAdapter。 可以使用数据源配置向导为 Customers 和 Orders 表创建 TableAdapter。

创建 TableAdapter

  1. 从**“数据”菜单中选择“添加新数据源”**。

  2. 在**“选择数据源类型”页上,选择“数据库”,然后单击“下一步”**。

  3. 在**“选择数据库模型”页上,选择“数据集”,然后单击“下一步”**。

  4. 在**“选择您的数据连接”**页上,使用下列过程之一:

    • 如果下拉列表中包含到 Northwind 示例数据库的数据连接,请选择该连接。

      - 或 -

    • 选择**“新建连接”**来配置到 Northwind 数据库的新数据连接。 有关更多信息,请参见如何:连接到数据库中的数据

  5. 选择数据连接后,单击**“下一步”**。

  6. 在**“将连接字符串保存到应用程序配置文件”页上,单击“下一步”**。

  7. 在**“选择数据库对象”页上,展开“表”**节点。

  8. 选择**“Customers”“Orders”表,然后单击“完成”**。

    **“NorthwindDataSet”被添加到您的项目中,并且在“数据源”窗口中“NorthwindDataSet”节点下出现“Customers”“Orders”**表。

将数据集和 TableAdapter 添加到 Form1

从**“工具箱”**将 CustomersTableAdapter、OrdersTableAdapter 和 NorthwindDataSet 的代表组件拖动到窗体,可以将其实例添加到该窗体。

用 Customers 表的数据填充 Customer 对象

  1. 从**“生成”菜单中选择“生成解决方案”**。

  2. 从**“工具箱”“NorthwindDataSet”拖动到“Form1”**上。

  3. 从**“工具箱”“CustomersTableAdapter”拖动到“Form1”**上。

  4. 从**“工具箱”“OrdersTableAdapter”拖动到“Form1”**上。

向 CustomersTableAdapter 添加一个查询以仅返回一些客户

在实际应用程序中,几乎不会返回整个数据表。 本演练中我们将返回最上面五个客户。

备注

通常,会传入一个参数以选择要返回的客户,但简洁起见,本演练中我们将对查询进行硬编码以仅返回五个客户,从而无需创建用于输入参数值的用户界面。

向 CustomersTableAdapter 添加更多查询

  1. 在**“解决方案资源管理器”**中,双击 NorthwindDataSet.xsd 文件。

    **“NorthwindDataset”“数据集设计器”**中打开。

  2. 右击**“CustomersTableAdapter”并选择“添加查询”**。

    TableAdapter 查询配置向导将打开。

  3. 保留**“使用 SQL 语句”的默认值,单击“下一步”**。

  4. 保留**“SELECT(返回行)”的默认值,单击“下一步”**。

  5. 用下面的代码替换 SQL 语句并单击**“下一步”**:

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. 清除**“填充 DataTable”**复选框。

  7. 将**“返回 DataTable”方法命名为 GetTop5Customers,然后单击“完成”**。

    “GetTop5Customers”查询被添加到“CustomersTableAdapter”

修改 OrdersTableAdapter 上的查询以便仅返回所需客户的订单

从数据库获取订单时,我们不希望返回整个订单表;仅希望返回特定客户的订单。 下面的过程详细介绍如何用新查询(与在上一步中向**“CustomersTableAdapter”**添加更多查询所执行的操作相对)重新配置 TableAdapter。

重新配置 TableAdapter 的主查询以返回单个客户的订单

  1. 右击**“OrdersTableAdapter”并选择“配置”**。

    TableAdapter 查询配置向导将打开。

  2. 用下面的代码替换 SQL 语句并单击**“下一步”**:

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. 清除**“填充 DataTable”**复选框。

  4. 将**“返回 DataTable”方法命名为“GetDataByCustomerID”,然后单击“完成”**。

    **“OrdersTableAdapter”的主 Fill 查询由“GetDataByCustomerID”**查询替换。

  5. 通过从**“生成”菜单中选择“生成解决方案”**来生成项目。

添加代码以将数据加载到 Customer 和 Order 对象中

若要将数据加载到自定义对象中,请执行返回新数据表的 TableAdapter 查询(而不是填充现有数据表的 TableAdapter 查询)。 然后,代码将循环访问表,并用客户信息填充每个 Customer 对象,并填充每个 Customer.Orders 集合中的所有订单。 注意将每个 Customer 对象添加到 CustomerBindingSource 的内部集合 (CustomerBindingSource.Add(currentCustomer)) 的方式。 BindingSource 提供了内置的 Customers 强类型集合,可通过 List 属性进行访问。

使用数据加载对象

  1. 从**“解决方案资源管理器”中,选择“Form1”,然后单击“查看代码”**。

  2. 用下面的代码替换**“Form1”**中的代码:

    Public Class Form1
        Private Sub LoadCustomers()
            Dim customerData As NorthwindDataSet.CustomersDataTable =
                CustomersTableAdapter1.GetTop5Customers()
    
            Dim customerRow As NorthwindDataSet.CustomersRow
    
            For Each customerRow In customerData
                Dim currentCustomer As New Customer()
                With currentCustomer
    
                    .CustomerID = customerRow.CustomerID
                    .CompanyName = customerRow.CompanyName
    
                    If Not customerRow.IsAddressNull Then
                        .Address = customerRow.Address
                    End If
    
                    If Not customerRow.IsCityNull Then
                        .City = customerRow.City
                    End If
    
                    If Not customerRow.IsContactNameNull Then
                        .ContactName = customerRow.ContactName
                    End If
    
                    If Not customerRow.IsContactTitleNull Then
                        .ContactTitle = customerRow.ContactTitle
                    End If
    
                    If Not customerRow.IsCountryNull Then
                        .Country = customerRow.Country
                    End If
    
                    If Not customerRow.IsFaxNull Then
                        .Fax = customerRow.Fax
                    End If
    
                    If Not customerRow.IsPhoneNull Then
                        .Phone = customerRow.Phone
                    End If
    
                    If Not customerRow.IsPostalCodeNull Then
                        .PostalCode = customerRow.PostalCode
                    End If
    
                    If Not customerRow.Is_RegionNull Then
                        .Region = customerRow._Region
                    End If
    
                End With
    
                LoadOrders(currentCustomer)
                CustomerBindingSource.Add(currentCustomer)
            Next
        End Sub
    
        Private Sub LoadOrders(ByRef currentCustomer As Customer)
            Dim orderData As NorthwindDataSet.OrdersDataTable =
                OrdersTableAdapter1.GetDataByCustomerID(currentCustomer.CustomerID)
    
            Dim orderRow As NorthwindDataSet.OrdersRow
    
            For Each orderRow In orderData
                Dim currentOrder As New Order()
                With currentOrder
                    .OrderID = orderRow.OrderID
                    .Customer = currentCustomer
    
                    If Not orderRow.IsCustomerIDNull Then
                        .CustomerID = orderRow.CustomerID
                    End If
    
                    If Not orderRow.IsEmployeeIDNull Then
                        .EmployeeID = orderRow.EmployeeID
                    End If
    
                    If Not orderRow.IsFreightNull Then
                        .Freight = orderRow.Freight
                    End If
    
                    If Not orderRow.IsOrderDateNull Then
                        .OrderDate = orderRow.OrderDate
                    End If
    
                    If Not orderRow.IsRequiredDateNull Then
                        .RequiredDate = orderRow.RequiredDate
                    End If
    
                    If Not orderRow.IsShipAddressNull Then
                        .ShipAddress = orderRow.ShipAddress
                    End If
    
                    If Not orderRow.IsShipCityNull Then
                        .ShipCity = orderRow.ShipCity
                    End If
    
                    If Not orderRow.IsShipCountryNull Then
                        .ShipCountry = orderRow.ShipCountry
                    End If
    
                    If Not orderRow.IsShipNameNull Then
                        .ShipName = orderRow.ShipName
                    End If
    
                    If Not orderRow.IsShippedDateNull Then
                        .ShippedDate = orderRow.ShippedDate
                    End If
    
                    If Not orderRow.IsShipPostalCodeNull Then
                        .ShipPostalCode = orderRow.ShipPostalCode
                    End If
    
                    If Not orderRow.IsShipRegionNull Then
                        .ShipRegion = orderRow.ShipRegion
                    End If
    
                    If Not orderRow.IsShipViaNull Then
                        .ShipVia = orderRow.ShipVia
                    End If
                End With
                currentCustomer.Orders.Add(currentOrder)
            Next
    
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, 
                               ByVal e As System.EventArgs) Handles MyBase.Load
    
            LoadCustomers()
        End Sub
    End Class
    
    using System;
    using System.Windows.Forms;
    
    namespace ObjectBindingWalkthrough
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.Load += Form1_Load;
            }
    
            private void LoadCustomers()
            {
                NorthwindDataSet.CustomersDataTable customerData = 
                    customersTableAdapter1.GetTop5Customers();
    
                foreach (NorthwindDataSet.CustomersRow customerRow in customerData)
                {
                    Customer currentCustomer = new Customer();
                    currentCustomer.CustomerID = customerRow.CustomerID;
                    currentCustomer.CompanyName = customerRow.CompanyName;
    
                    if (customerRow.IsAddressNull() == false)
                    {
                        currentCustomer.Address = customerRow.Address;
                    }
    
                    if (customerRow.IsCityNull() == false)
                    {
                        currentCustomer.City = customerRow.City;
                    }
    
                    if (customerRow.IsContactNameNull() == false)
                    {
                        currentCustomer.ContactName = customerRow.ContactName;
                    }
    
                    if (customerRow.IsContactTitleNull() == false)
                    {
                        currentCustomer.ContactTitle = customerRow.ContactTitle;
                    }
    
                    if (customerRow.IsCountryNull() == false)
                    {
                        currentCustomer.Country = customerRow.Country;
                    }
    
                    if (customerRow.IsFaxNull() == false)
                    {
                        currentCustomer.Fax = customerRow.Fax;
                    }
    
                    if (customerRow.IsPhoneNull() == false)
                    {
                        currentCustomer.Phone = customerRow.Phone;
                    }
    
                    if (customerRow.IsPostalCodeNull() == false)
                    {
                        currentCustomer.PostalCode = customerRow.PostalCode;
                    }
    
                    if (customerRow.IsRegionNull() == false)
                    {
                        currentCustomer.Region = customerRow.Region;
                    }
    
                    LoadOrders(currentCustomer);
                    customerBindingSource.Add(currentCustomer);
                }
            }
    
    
            private void LoadOrders(Customer currentCustomer)
            {
                NorthwindDataSet.OrdersDataTable orderData = 
                    ordersTableAdapter1.GetDataByCustomerID(currentCustomer.CustomerID);
    
                foreach (NorthwindDataSet.OrdersRow orderRow in orderData)
                {
                    Order currentOrder = new Order();
                    currentOrder.OrderID = orderRow.OrderID;
    
                    if (orderRow.IsCustomerIDNull() == false)
                    {
                        currentOrder.CustomerID = orderRow.CustomerID;
                    }
    
                    if (orderRow.IsEmployeeIDNull() == false)
                    {
                        currentOrder.EmployeeID = orderRow.EmployeeID;
                    }
    
                    if (orderRow.IsFreightNull() == false)
                    {
                        currentOrder.Freight = orderRow.Freight;
                    }
    
                    if (orderRow.IsOrderDateNull() == false)
                    {
                        currentOrder.OrderDate = orderRow.OrderDate;
                    }
    
                    if (orderRow.IsRequiredDateNull() == false)
                    {
                        currentOrder.RequiredDate = orderRow.RequiredDate;
                    }
    
                    if (orderRow.IsShipAddressNull() == false)
                    {
                        currentOrder.ShipAddress = orderRow.ShipAddress;
                    }
    
                    if (orderRow.IsShipCityNull() == false)
                    {
                        currentOrder.ShipCity = orderRow.ShipCity;
                    }
    
                    if (orderRow.IsShipCountryNull() == false)
                    {
                        currentOrder.ShipCountry = orderRow.ShipCountry;
                    }
    
                    if (orderRow.IsShipNameNull() == false)
                    {
                        currentOrder.ShipName = orderRow.ShipName;
                    }
    
                    if (orderRow.IsShippedDateNull() == false)
                    {
                        currentOrder.ShippedDate = orderRow.ShippedDate;
                    }
    
                    if (orderRow.IsShipPostalCodeNull() == false)
                    {
                        currentOrder.ShipPostalCode = orderRow.ShipPostalCode;
                    }
    
                    if (orderRow.IsShipRegionNull() == false)
                    {
                        currentOrder.ShipRegion = orderRow.ShipRegion;
                    }
    
                    if (orderRow.IsShipViaNull() == false)
                    {
                        currentOrder.ShipVia = orderRow.ShipVia;
                    }
                    currentCustomer.Orders.Add(currentOrder);
                }
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                LoadCustomers();
            }
    
        }
    }
    

测试应用程序

测试应用程序

  1. 按 F5 运行该应用程序。

  2. 窗体打开,并以示例数据填充 DataGridView 控件。

  3. DataGridView 中导航客户,以显示与其关联的订单。

后续步骤

在应用程序中添加功能

请参见

概念

准备应用程序以接收数据

将数据获取到应用程序

在 Visual Studio 中将控件绑定到数据

在应用程序中编辑数据

Visual Studio 中的对象绑定

保存数据

其他资源

连接到 Visual Studio 中的数据

数据演练