Practical Learning: Binding a Combo Box
|
|
- To get the database used in this exercise, start the Microsoft SQL Server
Management Studio and log in to the server
- On the main menu, click File -> New -> Query With Current Connection
- To create the database, type the following:
CREATE DATABASE StudentBinding;
GO
USE StudentBinding;
GO
CREATE TABLE Genders
(
GenderID int identity(1,1) PRIMARY KEY,
Gender varchar(20)
);
GO
INSERT INTO Genders(Gender) VALUES('Female');
GO
INSERT INTO Genders(Gender) VALUES('Male');
GO
INSERT INTO Genders(Gender) VALUES('Unknown');
GO
CREATE TABLE Students
(
StudentID int identity(1,1) PRIMARY KEY,
FirstName varchar(20),
LastName varchar(20) NOT NULL,
GenderID int
);
GO
INSERT INTO Students(FirstName, LastName, GenderID)
VALUES('Helene', 'Mukoko', 1);
GO
INSERT INTO Students(FirstName, LastName, GenderID)
VALUES('Gertrude', 'Wachs', 3);
GO
INSERT INTO Students(FirstName, LastName, GenderID)
VALUES('Peter', 'Lansome', 2);
GO
INSERT INTO Students(FirstName, LastName, GenderID)
VALUES('Paul', 'Motto', 2);
GO
INSERT INTO Students(FirstName, LastName, GenderID)
VALUES('Hermine', 'Ngaleu', 1);
GO
|
- Press F5 to execute
- Start Microsoft Visual Studio 2005
- To create a new application, on the main menu, click File -> New ->
Project...
- In the Projects list, select Visual C++ and, in the Templates list, click
Windows Forms Application
- Set the Name to StudentBinder1 and click OK
- On the main menu, click Data -> Add New Data Source
- In the first page of the wizard, make sure Database is selected and click
Next
- In the second page of the wizard, click New Connection
- For the server name, type (local)
- For the Database Name, select StudentBinding
- Click OK
- In the second page of the wizard, make sure ServerName.StudentBing.dbo
is selected in the combo box and click Next
- In the third page of the wizard, click the Tables check (that will select
both tables of our database)
- Set the DatasetName to dsStudents
- Click Finish
- From the Data Source window, click Students and click the arrow of its
combo box to select Details
- Drag Students and drop it on the form
- Delete the GenderID text box and customize the design
of the form as you see fit
- On the Toolbox, in the Data section, click BindingSource and drop it on
the form
- Change its properties as follows:
Name: bsGenders
DataSource: dsStudents
DataMember: Genders
- Add a combo box to the form and specify its properties as follows:
|
Name |
DataSource |
DisplayMember
|
ValueMember |
DataBindings -> SelectedValue |
cboGenders |
bsGenders |
Gender
|
GenderID |
StudentsBindingSource - GenderID |
|
- Execute the application to see the result
|
|