Free Programming Tutorials & Source Code

 
  • Increase font size
  • Default font size
  • Decrease font size
Home Visual Basic.NET Auto-Fill ComboBox Using VB.Net

Auto-Fill ComboBox Using VB.Net

E-mail
(4 votes, average: 5.00 out of 5)


ComboBox are anywhere in your application. It’s been a good choice for many programmers over the ListBox. However, making this control searchable is a great idea, whenever you have a long list of data. In this example, you will learn how to implement an auto-fill combo cbox. When you type a letter in it, I will return all data starting by this letter. In other word, it will optimize your search to get what you’re looking for.

Private Sub frmCombo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' Retrieve Data from the Database
Dim appPath As String = Mid(Application.ExecutablePath, 1, Len(Application.ExecutablePath) - 14)
Dim strConn As String = "Provider=Microsoft.JET.OLEDB.4.0;Data Source = " + AppPath + "myDatabase.mdb"
Dim conn As System.Data.OleDb.OleDbConnection = _
New System.Data.OleDb.OleDbConnection(strConn)

conn.Open()
Dim ds As New DataSet
Dim sqlStr As String
Dim cmd As System.Data.OleDb.OleDbCommand
Dim da As System.Data.OleDb.OleDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter

' Fill data into Dataset
Dim dr As DataRow

Dim dt As DataTable
With da
.TableMappings.Add("Table", "Users")
sqlStr = "Select Name from Users "
cmd = New System.Data.OleDb.OleDbCommand(sqlStr, conn)
cmd.CommandType = CommandType.Text
.SelectCommand = cmd
.Fill(ds)
.Dispose()
End With

ds.AcceptChanges()
dt = ds.Tables.Item(0)
ds.Dispose()
conn.Close()

'Fill ComboBox by Names
cbUsers.Text = ""
cbUsers.Items.Clear()
cbUsers.BeginUpdate()

' Load Names into the ComboBox Control
For Each dr In dt.Rows
cbUsers.Items.Add(dr("Name").ToString)
Next
cbUsers.EndUpdate()
End Sub

' Search the ComboBox by using the event "TextChanged"

Private Sub cbUsers_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cbUsers.TextChanged

Dim cIndex As Integer, Flag As Boolean
Dim cbox As ComboBox = sender

Dim ctxt As String = cbox.Text
Dim cCursor As Integer = cbox.SelectionStart

' If Cursor does not stay on the beginning of text cbox.
If cCursor <> 0 Then
Flag = False

' Loop through the ComboBox cbox to find the appropriate entry
For cIndex = 0 To cbox.Items.Count - 1
If UCase(Mid(cbox.Items(cIndex), 1, cCursor)) = UCase(Mid(ctxt, 1, cCursor)) Then
cbox.Text = cbox.Items(cIndex)
cbox.SelectionStart = cCursor
Flag = True
Exit For
End If
Next

' Returns the previous value of cbox when no entry found.
If Not Flag Then
cbox.Text = Mid(ctxt, 1, cCursor - 1) + Mid(ctxt, cCursor + 1)
cbox.SelectionStart = cCursor - 1
End If
End If

End Sub