AutoComplete ComboBox from Database in Windows Application using C# and VB.Net

Last Reply 2 months ago By kalpesh

Posted 2 months ago

I want to search a name that contains 'john' in any where . That means if I type 'john' in combo it will show all matching names  like tom john, john joseph, alex baby john etc in combo. I am workin with c# windows application.

You are viewing reply posted by: kalpesh 2 months ago.
Posted 2 months ago Modified on 2 months ago

Refer the below sample code for your reference and implement it as per your code logic.

Design

Namespace

C#

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

VB.Net

Imports System.Data.SqlClient

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQL2005;Initial Catalog=Northwind;uid=sa;pwd=pass@123;"))
    {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(@"SELECT ContactName FROM Customers", conn))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                foreach (DataRow row in dt.Rows)
                {
                    this.comboBox1.Items.Add(row["ContactName"]);
                }
            }
        }
    }

    this.comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
}

VB.Net

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Using conn As SqlConnection = New SqlConnection("Data Source=.\SQL2005;Initial Catalog=Northwind;uid=sa;pwd=pass@123;")
        conn.Open()
        Using cmd As SqlCommand = New SqlCommand("SELECT ContactName FROM Customers", conn)
            Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)

                For Each row As DataRow In dt.Rows
                    Me.comboBox1.Items.Add(row("ContactName"))
                Next
            End Using
        End Using
    End Using

    Me.comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
    Me.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
End Sub

Screenshot