This tutorial will teach you how to create an auto-complete ComboBox in a WinForm application. Auto-complete ComboBox is very useful when there are too many items in it.

Auto-complete ComboBox using VB.NET

First, we need to create a SQL Server database:

Design View

Table-Programming-Language-Design

Data View

Related

Auto-Complete ComboBox Using C#

Now open visual studio and create a WinForms application in Visual basic.NET, then add a ComboBox control to the main form.

autoComplete-Combo-WinForm

Now use the code below to bind the ComboBox.

VB.NET

   Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

       Try

           Dim strcon As String = "Data Source=YourHostName;Initial Catalog=TutorialsPanel;Integrated Security=True;Pooling=False"
           Dim conn As SqlConnection = New SqlConnection(strcon)

           conn.Open()
           Dim strSQL As String
           Dim cmd As SqlCommand

           Dim da As SqlDataAdapter = New SqlDataAdapter
           Dim dt As New DataTable

           strSQL = "Select * From ProgrammingLanguage Order by LanguageName ASC"
           cmd = New SqlCommand(strSQL, conn)
           cmd.CommandType = CommandType.Text
           da.SelectCommand = cmd
           da.Fill(dt)
           conn.Close()

           cbAutoCompleteVB.DataSource = dt
           cbAutoCompleteVB.DisplayMember = "LanguageName"

       Catch ex As Exception
       MessageBox.Show(ex.Message)

       End Try
   End Sub

Then add the code below to the KeyPress event of the ComboBox.

VB.NET

Private Sub cbAutoCompleteVB_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbAutoCompleteVB.KeyPress

    cbAutoCompleteVB.DroppedDown = True
    If (Char.IsControl(e.KeyChar)) Then Return
    Dim Str As String = cbAutoCompleteVB.Text.Substring(0, cbAutoCompleteVB.SelectionStart) + e.KeyChar
    Dim Index As Integer = cbAutoCompleteVB.FindStringExact(Str)

    If Index = -1 Then
        Index = cbAutoCompleteVB.FindString(Str)
    End If

    Me.cbAutoCompleteVB.SelectedIndex = Index
    Me.cbAutoCompleteVB.SelectionStart = Str.Length
    Me.cbAutoCompleteVB.SelectionLength = Me.cbAutoCompleteVB.Text.Length - Me.cbAutoCompleteVB.SelectionStart
    e.Handled = True
End Sub

Run the application

autoComplete-Combo

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.