演练:连接到对象中的数据

更新:2007 年 11 月

本演练演示如何创建对象以保存客户和订单数据,然后根据这些对象创建对象数据源。对象数据源显示在“数据源”窗口中,在该窗口中,项被拖动到窗体上,从而创建绑定到对象的公共属性中的数据的控件。本演练还演示如何使用 TableAdapter 从数据库获取数据并填充对象。

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

说明:

需要生成包含对象的项目,以便该对象显示在“数据源配置向导”中。如果向导中没有该对象,则重新生成包含所需对象的项目。

本演练演示如下任务:

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

  • 创建表示客户和订单的示例对象。

  • 使用“数据源配置向导”根据示例对象在应用程序中创建和配置对象数据源。

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

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

  • 编辑 TableAdapter 的主查询。

  • 向 TableAdapter 添加查询。

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

创建项目

创建新的 Windows 应用程序项目

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

  2. 创建一个名为“ObjectBindingWalkthrough”的“Windows 应用程序”,然后单击“确定”。有关更多信息,请参见创建基于 Windows 的应用程序

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

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

创建 Customer 对象

创建 Customer 对象

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

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

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

    说明:

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

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

创建 Order 对象

创建 Order 对象和 Orders 集合

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

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

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

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

创建对象数据源

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

创建对象数据源

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

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

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

  4. 展开“ObjectBindingWalkthrough”节点并选择“Customer”对象。

    说明:

    如果“Customers”对象不可用,则单击“取消”,然后从“生成”菜单中选择“生成 ObjectBindingWalkthrough”。成功生成项目后,重新启动向导(步骤 2),自定义对象即会出现。

  5. 单击“完成”。

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

创建数据绑定窗体

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

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

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

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

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

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

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

创建 TableAdapter

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

  2. 在“选择数据源类型”页上选择“数据库”。

  3. 在“选择数据连接”页面上,执行以下操作之一:

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

  5. 在“选择数据库对象”页面上展开“表”节点。

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

    “NorthwindDataSet”被添加到您的项目中,并且在“数据源”窗口中“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 提供可通过 List 属性访问的 Customers 内置强类型集合。

使用数据加载对象

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

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

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

测试应用程序

测试应用程序

  1. 按 F5 运行应用程序。

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

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

后续步骤

在应用程序中添加功能

请参见

概念

Visual Studio 中的对象绑定

其他资源

连接到 Visual Studio 中的数据

准备应用程序以接收数据

将数据获取到应用程序

在 Windows 应用程序中的窗体上显示数据

在应用程序中编辑数据

保存数据

数据演练