7.11. Populating a Windows Forms ComboBox
Problem
You need to populate a ComboBox
from
a database, bind a field in a database to the
ComboBox
so that the correct value is selected
from the list, and use the value selected in the
ComboBox
to update the database.
Solution
You must:
Fill a
ComboBox
from a database (pay attention to the difference between theSelectedIndex
andSelectedValue
).Bind a
ComboBox
to a field in a result set so that the value is selected in theComboBox
corresponding to the value in a field for the record displayed.Use the selection events returned by the
ComboBox
.Update the database with the value selected in the
ComboBox
.
The schema of table TBL0711 used in this solution is shown in Table 7-11.
Table 7-11. TBL0711 schema
Column name |
Data type |
Length |
Allow nulls? |
---|---|---|---|
Id |
|
4 |
No |
ComboBoxItemId |
|
4 |
No |
Field1 |
|
50 |
Yes |
The schema of table TBL0711_ComboBoxSource used in this solution is shown in Table 7-12.
Table 7-12. TBL0711_ComboBoxSource schema
Column name |
Data type |
Length |
Allow nulls? |
---|---|---|---|
ComboBoxItemId |
|
4 |
No |
Description |
|
50 |
No |
The sample code contains seven event handlers:
Form.Load
Sets up the sample by creating a
DataAdapter
with the logic to select all records from table TBL0709 in the sample database and to update changes made back to the database. TheDataAdapter
is used to fill aDataTable
in a newDataSet
with the schema and data from TBL0709. ADataTable
is filled from tableTBL0709_ComboBoxSource
and added to the ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.