This is an example of how to fill a combo box with
data from a table.
|
Practical
Learning: Binding a Combo Box
|
|
- First complete the lesson on regular data
binding and open it
- 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 |
- Save it as Genders and fill it up as follows:
GenderID |
Gender |
|
Unknown |
|
Female |
|
Male |
- Close the table
- 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 |
|
|
- Save the table as Persons
- Right-click GenderID and click Relationships...
- Set the Primary Key Table and the Foreign Key Table fields as GenderID
- Click Close
You can fill out the table with a few records
- Open the ExoADO1 application
- Add a new combo box to the form as follows:
|
Control |
Name |
Text |
Additional Properties |
Label |
|
Gender: |
|
ComboBox |
cboGender |
|
DropDownStyle: DropDownList |
|
- To update the data source, right-click sqlDataAdapter1 and click
Configure Data Adapter...
- Click Next
- In the Data Adapter Configuration Wizard, in the combo box,
select Server.People.dbo and click Next
- Accept the default Use SQL Statements radio button and click Next
- Change the statement to
SELECT PersonID, FirstName, LastName, GenderID FROM Persons
|
- Click Next and click Finish
- To create a data source for the combo box, from the Data section of
the Toolbox, click SqlDataAdapter and click the form
- Click Next
- In the combo box, select Server.People.dbo and click Next
- Accept the default Use SQL Statements radio button and click Next
- Click Query Builder...
- From the Tables property page of the Add Table dialog box, click
Genders. Click Add and click Close
- In the upper section of the Query Builder window, click the GenderID and
the Gender check boxes
- Click OK
- Click Next and click Finish
- To create a data set for the genders, right-click sqlDataAdapter2
and click Generate Dataset...
- Accept the Existing radio button and accept the Genders check box
- Click OK
- On the form, click the combo box
- In the Properties window, set the properties as follows:
DataSource: dsPersons1.Genders
DisplayMember: Gender
ValueMember: GenderID
DataBindings -> SelectedValue: dsPersons1 - Persons.GenderID
- Double-click an empty area of the form and change the Load event as
follows:
private: System::Void Form1_Load(System::Object * sender,
System::EventArgs * e)
{
sqlDataAdapter2->Fill(this->dsPersons1, "Genders");
sqlDataAdapter1->Fill(dsPersons1, "Persons");
}
|
- Press Ctrl + F5 to test the application
|
|