Home > Articles > Programming > Windows Programming

This chapter is from the book

Complex Data Binding in Windows Forms

In the next example, you will build a quick-and-dirty Windows Form that will display all customers in a bound ListBox and the customer's associated Orders in a bound DataGrid. A more complex DataSet will be needed that provides the relationship path to traverse from customers to orders using the primary key of Customers (CustomerID) to foreign key in Orders (CustomerID). You will have to do data bindings for both the ListBox control and the DataGrid control. This example is one of the classic data binding scenarios described earlier.

Create a New Project in VS .NET

  1. Create a new project in VS .NET by choosing File, New, and then choosing the Project option. Or, you can just modify the "ADO.NET24hoursDB" that we just created for simple binding. If you choose to modify this one, delete all of the Forms objects, methods, and so on that we added so that you start from a clean slate. This will include deleting the DataSet schema that is shown in the Solution Explorer.

  2. When the New Project dialog box appears, choose Visual Basic Projects (or Visual C# Projects) and Windows Applications. Name this project "ADO.NET24hoursE". This creates a default form for you to start from.

Add the Data Connection and Two Data Adapters

You will need to access both the Customers table and the Orders table, so two data adapters will be created, each populating different controls but using one database connection.

  1. From the Data tab of the Toolbox, drag a SQLDataAdapter object into your form. This will automatically invoke the Data Adapter Configuration Wizard. Both the data connection and the data adapter can be fully configured here.

    1. The wizard starts with the Choose Your Data Connection dialog box. If you already have a connection defined in your project, it will be placed in the dialog box; otherwise, choose to create a new connection and specify the appropriate connection information (test the connection as well).

    2. Choose the Use SQL Statements option.

    3. You will be presented with a Generate the SQL Statements dialog box where you will simply type in a valid SQL statement, or you can use the Query Builder option to formulate the SQL query. For our example, just type in the following query:

    4.   SELECT CustomerID, CompanyName FROM Customers
    5. Finally, the wizard will show you the tasks that it has done and indicate whether the SqlDataAdapter has been configured successfully (it should be named SqlDataAdapter1 along with a SqlConnection name SqlConnection1.

  2. Okay, we need one more data adapter for access to the Orders table. Drag another SqlDataAdapter object onto the form.

    1. Again, the wizard starts with the Choose Your Data Connection dialog box.

    2. Choose the Use SQL Statements option.

    3. You will be presented with a Generate the SQL Statements dialog box where you will type the following query:

    4.   SELECT OrderID, CustomerID, OrderDate, ShipVia, Freight, ShipName 
        FROM Orders
  3. And lastly, the wizard will show you the tasks that it has done and indicate whether the SqlDataAdapter has been configured successfully (it should be named SqlDataAdapter2).

Generate a DataSet

Now that the SqlDataAdapter and DataConnection objects have been configured and added to the form, you must generate a DataSet and then add an instance of this DataSet to the form.

  1. From the Data menu in Visual Studio, simply choose the Generate Dataset option. The resulting dialog box can be seen in Figure 9.6.

  2. Figure 9.6 Generating a new dataset for the form.

  3. Now, just choose to create a new dataset using the name "CustOrdDS" (as also seen in Figure 9.6) that it provides (DataSet1). Make sure you have checked the Customers table, Orders table, and checked the Add Dataset to Designer box. Click OK.

  4. When the process finishes, a DataSet instance named CustOrdDS1 will be on the form and a dataset schema will be in the Solutions Explorer (named CustOrdDS.xsd).

  5. You're not quite done yet. There must also be a way for the schema to know that there is a parent/child relationship between Customers and Orders. You do this by adding a Relation object onto the Orders table in the schema. First, double-click on the CustOrdDS.xsd schema file in the Solutions Explorer. This takes you immediately into the XML Schema editor. Figure 9.7 shows the two tables that are part of the CustOrdDS.xsd schema.

  6. Next, drag a Relation object onto the Orders table (this is the child side of the parent/child relationship). You are immediately put into the Edit Relation dialog box.

  7. Verify that the name of the Relation defaults to CustomersOrders, the Parent element is Customers, the Child element is Orders, and the Key Fields and Foreign Key Fields both are CustomerID. Nothing else should be checked at this point. Figure 9.8 shows the values in the Edit Relation dialog box. Click OK when you are satisfied that all is correct.

  8. Figure 9.7 XML Schema editor—CustOrdDS.xsd schema file.

    Figure 9.8 The Edit Relation dialog box for the CustomersOrders relation.

  9. The XML Schema editor should now show a one-to-many relationship line between the Customers and Orders table as seen in Figure 9.9. The following code is the content of the CustOrdDS.xsd XML Schema file that now reflects the new relationship:

  10. <?xml version="1.0" standalone="yes" ?>
    <xs:schema id="CustOrdDS" targetNamespace=
    xmlns:mstns="http://www.tempuri.org/CustOrdDS.xsd" xmlns=
    attributeFormDefault="qualified" elementFormDefault="qualified">
     <xs:element name="CustOrdDS" msdata:IsDataSet="true">
      <xs:choice maxOccurs="unbounded">
      <xs:element name="Customers">
         <xs:element name="CustomerID" type="xs:string" />
         <xs:element name="CompanyName" type="xs:string" />
     <xs:element name="Orders">
        <xs:element name="OrderID" msdata:ReadOnly="true"
    type="xs:int" />
      <xs:element name="CustomerID" type="xs:string" minOccurs="0" />
      <xs:element name="OrderDate" type="xs:dateTime" minOccurs="0" />
      <xs:element name="ShipVia" type="xs:int" minOccurs="0" />
      <xs:element name="Freight" type="xs:decimal" minOccurs="0" />
      <xs:element name="ShipName" type="xs:string" minOccurs="0" />
    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Customers" />
      <xs:field xpath="mstns:CustomerID" />
    <xs:unique name="Orders_Constraint1" msdata:ConstraintName="Constraint1" 
      <xs:selector xpath=".//mstns:Orders" />
      <xs:field xpath="mstns:OrderID" />
    <xs:keyref name="CustomersOrders" refer="mstns:Constraint1">
      <xs:selector xpath=".//mstns:Orders" />
      <xs:field xpath="mstns:CustomerID" />
    </xs :schema>

    Figure 9.9 The XML Schema editor, showing the new relationship between Customers and Orders.

Adding the ListBox and DataGrid Controls

The next step is to add the ListBox control to display the Company Names and the DataGrid control to display the Order information associated with these companies.

  1. First, let's create the ListBox to display all of the Company Names from the Customers table.

    1. Drag a ListBox object from the Windows Forms tab of the Toolbox onto the Form.

    2. Press F4 to go right to the properties of this ListBox.

    3. For the DataSource property, you will need to select the CustOrdDS1 data source.

    4. For the DisplayMember property, you will select Customers, expand this node, and select CustomerName. Figure 9.10 shows the complete ListBox property specifications for this example.

  2. Now, let's create the DataGrid control to display all of the Orders that are associated with a particular Company that is selected. As the form is running, whenever you move from one CompanyName to another, the form's data binding framework queries the data relation object so it can provide the correct Orders (for that company).

    1. Drag a DataGrid object from the Windows Forms tab of the toolbox onto the Form.

    2. Press F4 to go right to the properties of this DataGrid.

    3. Figure 9.10 ListBox property specifications.

    4. For the DataSource property, you will need to select the CustOrdDS1 data source.

    5. And, for the DisplayMember property, you will select and expand Customers, and then select CustomersOrders. This is actually the data relation (and the Orders table). So, we are binding to the data relation object! Figure 9.11 shows the DataMember property specifications.

  3. Go ahead and add labels on the top of the ListBox and the DataGrid if you want. Figure 9.11 also shows this completed form with labels.

  4. Figure 9.11 Completed ListBox, DataGrid, and labels within VS .NET.

Properties or Methods Binding

For ListBox controls, you can bind the control to a DataSet class using the DataSource and DisplayMember properties as you have seen in our Windows Forms example:

Me.ListBox1.DataSource = Me.CustOrdDS1
Me.ListBox1.DisplayMember = "Customers.CompanyName" 

Or, you can use the DataBinding method programmatically to achieve the same results.

Me.ListBox1.DataBindings.Add(New System.Windows.Forms.Binding
("SelectedItem", Me.CustOrdDS1, "Customers.CompanyName"))

For DataGrid controls, you bind the control to a DataSet class using the DataSource and DataMember properties:

Me.DataGrid1.DataMember = "Customers.CustomersOrders"
Me.DataGrid1.DataSource = Me.CustOrdDS1

Or, use the SetDataBinding method programmatically to achieve the same results:


Add Code to Populate the DataSet

Now we are ready to complete the application by adding the code to fill the DataSet. We have determined that the best time to fill the DataSet is when the form is brought up (at form load time).

Just double-click on the form to create a handler for the form's Load event. You will need to clear the DataSet first, and then fill each data adapter that we defined.


Test It!

That's it! Now just hit the F5 key and test your application. When the form comes up, it should already display Company Names in the ListBox. When you select one of these (with orders), the DataGrid will display all related orders for that company.

In Figure 9.12, you can see the form displaying a valid customer's information successfully.

Figure 9.12 The Get Customer Forms application, showing complex DataGrid binding.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020