FunctionX Practical Learning Logo

Combo Box Data Binding


 

Introduction

This is an example of how to fill a combo box with data from a table.

Practical LearningPractical Learning: Opening the Query Analyzer

  1. First complete the lesson on regular data binding and open it
  2. Unless you already have a table named Genders in the People database, create a new table in Design view as follows:
     
    Column Name Data Type Length Addition Properties
    GenderID int   Set Primary Key
    Identity: Yes
    Gender varchar 20 Allow Nulls: Unchecked
  3. Save it as Genders and fill it up as follows:
     
    GenderID Gender
      Unknown
      Female
      Male
  4. Close the table
  5. Open the Persons table in Design view and, in the first empty column, create a new field as follows:
     
    Column Name Data Type Length Addition Properties
    PersonID      
    FirstName      
    LastName      
    GenderID int    
  6. Save the table as Persons
  7. Right-click GenderID and click Relationships...
  8. Set the Primary Key Table and the Foreign Key Table fields as GenderID
     
  9. Click Close
    You can fill out the table with a few records
     

 

 

 

Creating a Data Bound Combo Box

.

Practical LearningPractical Learning: Creating a Database Using the Query Analyzer

  1. Open the ExoADO1 application
  2. Click the text box on the right side of Gender and press Delete
  3. Add a new combo box where the GenderID text box was:
     
    People Form
    Control Name Text Additional Properties
    ComboBox cboGender   DropDownStyle: DropDownList
  4. To create a data source for the combo box, from the Data section of the Toolbox, click SqlDataAdapter and click the form
  5. Click Next
  6. In the combo box, select Server.People.dbo and click Next
  7. Accept the default Use SQL Statements radio button and click Next
  8. Click Query Builder...
  9. From the Tables property page of the Add Table dialog box, click Genders. Click Add and click Close
  10. In the upper section of the Query Builder window, click the GenderID and the Gender check boxes
  11. Click OK
  12. Click Next and click Finish
  13. To create a data set for the genders, right-click sqlDataAdapter2 and click Generate Dataset...
  14. Accept the Existing radio button and accept the Genders check box
  15. Click OK
  16. On the form, click the combo box
  17. In the Properties window, set the properties as follows:
    DataSource: dsPersons1.Genders
    DisplayMember: Gender
    ValueMember: GenderID
    DataBindings -> SelectedValue: dsPersons1 - Persons.GenderID
  18. Double-click an empty area of the form and change the Load event as follows:
     
    private void Form1_Load(object sender, System.EventArgs e)
    {
    	sqlDataAdapter2.Fill(dsPersons1, "Genders");
    	sqlDataAdapter1.Fill(dsPersons1, "Persons");
    }
  19. Press Ctrl + F5 to test the application
 

Home Copyright © 2004 FunctionX, Inc.