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
ComboBoxfrom a database (pay attention to the difference between theSelectedIndexandSelectedValue).Bind a
ComboBoxto a field in a result set so that the value is selected in theComboBoxcorresponding 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.LoadSets up the sample by creating a
DataAdapterwith the logic to select all records from table TBL0709 in the sample database and to update changes made back to the database. TheDataAdapteris used to fill aDataTablein a newDataSetwith the schema and data from TBL0709. ADataTableis filled from tableTBL0709_ComboBoxSourceand added to the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access