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 the SelectedIndex and SelectedValue).

  • Bind a ComboBox to a field in a result set so that the value is selected in the ComboBox 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

int

4

No

ComboBoxItemId

int

4

No

Field1

nvarchar

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

int

4

No

Description

nvarchar

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. The DataAdapter is used to fill a DataTable in a new DataSet with the schema and data from TBL0709. A DataTable is filled from table TBL0709_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.