Walkthrough: Connecting to Data in Objects (Windows Forms)

This walkthrough creates objects to hold customer and order data, together with an object data source for each object. The object data source appears in the Data Sources window: items are dragged from that window onto a form to create controls that are bound to the data in the public properties for each object. The walkthrough also shows how to use TableAdapters to fetch data from the database and populate the objects.

The object data source is created by running the Data Source Configuration Wizard and selecting Object as the type of data source. After you complete the Data Source Configuration Wizard, the public properties of the object are available in the Data Sources Window and they can be dragged onto your form.

Tasks illustrated in this walkthrough include the following:

  • Creating a new Windows Forms Application project.

  • Creating custom objects to represent customers and orders.

  • Creating and configuring an object data source that is based on the custom objects by using the Data Source Configuration Wizard.

  • Adding controls to a form that are bound to the data in the custom objects.

  • Creating a dataset with TableAdapters to move data between your objects and the database.

  • Editing a TableAdapter's main query.

  • Adding queries to a TableAdapter.

  • Populating your objects with data from the database.

To create the new Windows Forms Application project

  1. From the File menu, create a New Project.

  2. In the Project Types pane, under the node for the language you want to use, click Windows.

  3. In the Templates pane, click Windows Forms Application.

  4. In the Name box, type ObjectBindingWalkthrough and click OK.

    The ObjectBindingWalkthrough project is created and added to Solution Explorer.

This walkthrough needs some objects to bind to. The first step is to create some sample objects to represent customers and orders. To represent customers we will create a Customer object that represents a single customer. To represent orders we will create an Order object, which represents a single order, and an Orders object, which represents a collection of Order objects. For the collection of Customer objects we will use the built-in collection in the BindingSource class (explained later in this walkthrough).

To create the Customer object

  1. On the Project menu, click Add Class.

  2. Name the new class Customer and click Add.

  3. Replace the code in the Customer class file with the following code:

    Note Note

    The Customer object contains an ordersCollection property of the type Orders. The editor will display a message stating Type 'Orders' is not defined. This message is expected and will disappear when you create the Order and Orders classes in the next section.

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

To create the Order object and Orders collection

  1. On the Project menu, select Add Class.

  2. Name the new class Order and click Add.

  3. Replace the code in the Order class file with the following code:

    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. From the File menu, choose Save All.

You can create a data source based on the objects created in the previous step by running the Data Source Configuration Wizard.

To create the object data source

  1. Build your project.

    Note Note

    You must build the project before objects in the project can be selected in the Data Source Configuration Wizard.

  2. Open the Data Sources window by clicking the Data menu and selecting Show Data Sources.

  3. Click Add New Data Source in the Data Sources window.

    The Data Source Configuration Wizard starts.

  4. On the Choose a Data Source Type page, select Object, and then click Next.

  5. On the Select the Data Objects page, expand the ObjectBindingWalkthrough nodes and select the check box next to the Customer object.

  6. Click Finish.

    The Customer object appears in the Data Sources window.

Controls bound to the Customer object are created by dragging items from the Data Sources window onto a form.

To create a form with controls bound to the object properties

  1. In Solution Explorer, select Form1, and click View Designer.

  2. Drag the Customer node from the Data Sources window onto Form1.

  3. Expand the Customer node and drag the Orders node from the Data Sources window onto Form1.

To move data between the objects and the database, we will use TableAdapters. You can create TableAdapters for the Customers and Orders tables by using the Data Source Configuration Wizard.

To create the TableAdapters

  1. From the Data menu, choose Add New Data Source.

  2. On the Choose a Data Source Type page, select Database, and then click Next.

  3. On the Choose a Database Model page, select Dataset, and then click Next.

  4. On the Choose Your Data Connection page, use one of the following procedures:

    • If a data connection to the Northwind sample database is available in the drop-down list, select it.

      -or-

    • Select New Connection to configure a new data connection to the Northwind database. For more information, see How to: Connect to Data in a Database.

  5. After you select a data connection, click Next.

  6. On the Save connection string to the Application Configuration file page, click Next.

  7. On the Choose your Database Objects page, expand the Tables node.

  8. Select the Customers and Orders tables, and then click Finish.

    The NorthwindDataSet is added to your project and the Customers and Orders tables appear in the Data Sources window under the NorthwindDataSet node.

You can add instances of the CustomersTableAdapter, OrdersTableAdapter, and NorthwindDataSet to the form by dragging their representative components from the Toolbox.

To fill the Customer objects with data from the Customers table

  1. From the Build menu, select Build Solution.

  2. Drag a NorthwindDataSet from the Toolbox onto Form1.

  3. Drag a CustomersTableAdapter from the Toolbox onto Form1.

  4. Drag an OrdersTableAdapter from the Toolbox onto Form1.

In real-world applications, you will likely never return the whole table of data. For this walkthrough we will return the top five customers.

Note Note

You would typically pass in a parameter to select which customers you want to return, but for brevity in this walkthrough we will hard-code the query to return only five customers and eliminate the need of creating a user interface for inputting parameter values.

To add an additional query to the CustomersTableAdapter

  1. In Solution Explorer, double-click the NorthwindDataSet.xsd file.

    The NorthwindDataSet opens in the Dataset Designer.

  2. Right-click the CustomersTableAdapter and select Add Query.

    The TableAdapter Query Configuration Wizard opens.

  3. Leave the default of Use SQL statements and click Next.

  4. Leave the default of SELECT which returns rows and click Next.

  5. Replace the SQL statement with the following and click Next:

    SELECT Top 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, 
    City, Region, PostalCode, Country, Phone, Fax 
    FROM Customers 
    
  6. Clear the Fill a DataTable check box.

  7. Name the Return a DataTable method GetTop5Customers and click Finish.

    The GetTop5Customers query is added to the CustomersTableAdapter.

When fetching orders from the database, we do not want to return the whole table of orders; we only want the orders for a specific customer. The following procedure details how to reconfigure a TableAdapter with a new query (as opposed to adding an additional query as we did to the CustomersTableAdapter in the previous step).

To reconfigure the TableAdapter's main query to return a single customer's orders

  1. Right-click the OrdersTableAdapter and choose Configure.

    The TableAdapter Query Configuration Wizard opens.

  2. Replace the SQL statement with the following and click Next:

    SELECT OrderID, CustomerID, EmployeeID, OrderDate, 
    RequiredDate, ShippedDate, ShipVia, Freight, 
    ShipName, ShipAddress, ShipCity, ShipRegion, 
    ShipPostalCode, ShipCountry 
    FROM Orders 
    WHERE CustomerID = @CustomerID
    
  3. Clear the Fill a DataTable check box.

  4. Name the Return a DataTable method GetDataByCustomerID and click Finish.

    The OrdersTableAdapter's main Fill query is replaced with the GetDataByCustomerID query.

  5. Build the project by selecting Build Solution from the Build menu.

To load data into our custom objects, you execute the TableAdapter queries that return new data tables (rather than using TableAdapter queries that fill existing data tables). The code then loops through the table and populates each Customer object with the customer information, in addition to populating all orders in each Customer.Orders collection. Notice how each Customer object is added to the internal collection of the CustomerBindingSource (CustomerBindingSource.Add(currentCustomer)). The BindingSource provides a built-in strongly typed collection of Customers that can be accessed through the List property.

To load the objects with data

  1. In Solution Explorer, select Form1, and click View Code.

  2. Replace the code in Form1 with the following code:

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

To test the application

  1. Press F5 to run the application.

  2. The form opens and the DataGridView controls are populated with the sample data.

  3. Navigate the customers in the DataGridView to display their associated orders.

To add functionality to your application

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft