Now a few more years under my belt... the following code will work with DropDownList or DropDown. Pulls the information from a single column in a database table. The flags will handle both a DropDownList or a DropDown. Drop down for AutoComplete and SuggestAppend.
Code:
Public Sub PopulateDropDownList(ByRef ControlName As ComboBox, _
ByVal TableName As String, _
ByVal ColumnName As String, _
Optional ByVal DropDown As Boolean = False, _
Optional ByVal DropDownList As Boolean = False)
Using SetDatabaseConnection As New SqlConnection(MSSQLConnection)
Dim Qry As String = "SELECT " & ColumnName & " FROM " & TableName
Dim Da As New SqlDataAdapter(Qry, SetDatabaseConnection)
Dim Ds As New DataSet
Try
Ds.Clear()
Da.Fill(Ds, TableName)
Dim AddBlankEntry As DataRow = Ds.Tables(TableName).NewRow
AddBlankEntry(ColumnName) = vbNullString
Ds.Tables(TableName).Rows.Add(AddBlankEntry)
With ControlName
If DropDown = True Then
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
Else
.AutoCompleteMode = AutoCompleteMode.None
End If
.DataSource = Ds.Tables(TableName)
.DisplayMember = ColumnName
.ValueMember = ColumnName
.SelectedItem = vbNullString
End With
Catch RangeEx As IndexOutOfRangeException
MessageBox.Show(RangeEx.Message, _
"Index Out Of Range Exception", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error, _
MessageBoxDefaultButton.Button1)
Catch CastEx As InvalidCastException
MessageBox.Show(CastEx.Message, _
"Invalid Cast Exception", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error, _
MessageBoxDefaultButton.Button1)
Catch ArgNullEx As ArgumentNullException
MessageBox.Show(ArgNullEx.Message, _
"Invalid Cast Exception", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error, _
MessageBoxDefaultButton.Button1)
End Try
End Using
End Sub
To use the code, just call the following in your form load event and change the boolean flags accordingly.
Code:
PopulateDropDownList(DropDownMenuControlName, "DatabaseTableName", "ColumnName", False, True)