Programmatically add data to a ComboBox from a database

How to change the ComboBox data source during program execution
7/17/2009 8:36:00 AM


An application required that a ComboBox be loaded with data and value members from a SQL database data table. During program execution the user could select either a local SQL data base or a remote database accessed via an internet connection. A populateComboBox method was created and the database connection string was passed in as a parameter.

A variable dataList is declared of type ArrayList. It will be filled with objects of type ComboBoxData. The ComboBoxData class has two properties; DisplayMember and ValueMember. They will be used to hold the DisplayMember and ValueMember properties for the ComboBox. The DataMember and ValueMember properties are passed in through the constructor of the ComboBoxData class.

code snippet 1 After dataList is declared the SQL connection parameters are initialized. The connection is opened and the display member and value member data is read from the data source. An instance of the ComboBoxData class is created with the values read from the data source. The new instance is then added to the dataList. The process is repeated until all items are read from the data source. If a ValueMember for the ComboBox is not required, the DisplayMember could be added directly to the dataList without using the ComboBoxData Class.

Now that we have the dataList containing the display and value members for the comboBox, the dataList is bound to the ComboBox with the ComboBox.DataSource property. The display and value members are then set with the ComboBox.DisplayMember and ComboBox.ValueMember properties.

code snippet 2 The SQL connection is invoked with a Using statement which guarantees that it will be disposed of correctly. Reading the data from the SQL data source is wrapped in a Try Catch Finally block so that if any errors occur, a flag can be set to prevent corrupted data from being loaded into the ComboBox.

The ValueMember of the selected item in the ComboBox is obtained with the ComboBox.SelectedValue property.

code snippet 3 A System.Data.SqlClient Imports statement is required to access the data base.

 

Development Tools

  • Visual Studio 2005
  •   .NET Framework 2.0
  •   Visual C# 2005
  •   Visual Basic 2005
  •   SQL Server 2005
  • MPLAB IDE
  •   C32 C Compiler
  •   MPASM Assembler