Search code examples
vb.netdatatabledatagridviewcomboboxoledb

How to make combobox autocomplete in VB.NET


How can I adjust my code below so that I make the ComboBox autocomplete?

Private Sub PopulateComboBox()
    Dim query As String = "SELECT DISTINCT PNM FROM GSD UNION SELECT DISTINCT PNM FROM GSG ORDER BY PNM"
    Try
        Using con As OleDbConnection = New OleDbConnection(cn)
            Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
                'Fill the DataTable with records from Table.
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)

                'Insert the Default Item to DataTable.
                Dim row As DataRow = dt.NewRow()

                row(0) = ""
                dt.Rows.InsertAt(row, 0)

                'Assign DataTable as DataSource.
                ComboBox1.DataSource = dt
                ComboBox1.DisplayMember = "PNM"
                ComboBox1.ValueMember = "PNM"
            End Using
        End Using
    Catch myerror As OleDbException
        MessageBox.Show("Error: " & myerror.Message)
    Finally
    End Try
End Sub

Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
    fillDataGridView1()
    fillDataGridView2()
End Sub

Solution

  • That depends what you exactly want and need.

    You can only change the autocomplete property in code, when the FORM_LOAD event is proceeding, after that the changes will not take effect.

    here are all three possibilities to manipulate the autocomplte

    the AutoCompleteMode determines what kind of autocomplete so you want.

    the rest is when you have an extra source for the autocompletio

        Dim source As New AutoCompleteStringCollection()
        source.AddRange(New String() _
                        {
                            "one",
                            "two",
                            "three",
                            "Four"
                        })
        With ComboBox1
            .AutoCompleteCustomSource = source
            .AutoCompleteMode = AutoCompleteMode.SuggestAppend
            .AutoCompleteSource = AutoCompleteSource.CustomSource
        End With