8.13. Binding Data to a Windows Forms Control
Problem
You need to populate a ComboBox from a database and bind a field in a database to the ComboBox so you can select its corresponding value.
Solution
You need to:
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.
Follow these steps:
Create a C# Windows Forms application named
BindWindowsFormSimpleControl.Add the following controls to the
Form1design surface:LabelwithTextproperty =Department:ComboBoxnameddepartmentComboBox
The completed layout of the Windows Form named Form1 is shown in Figure 8-25.

Figure 8-25. Layout for Form1 in BindWindowsFormSimpleControl solution
The C# code in Form1.cs in the project BindWindowsFormSimpleControl is shown in Example 8-25. The solution binds a DataView containing the DepartmentID and Name for all records in the HumanResources.Department table in AdventureWorks to the ComboBox. The handler for the SelectedIndexChanged event of the ComboBox control displays the values for the SelectedValue and SelectedText properties of the ComboBox after its selected item has changed.
Example 8-25. File: Form1.cs for BindWindowsFormSimpleControl solution
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