Windows Forms: How to make a TextBox AutoComplete in C#

AutoComplete TextBox in C# using sql database

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "AutoCompleteTextBox" and then click OK

c# auto complete textboxStep 2: Design your form as below

auto complete textbox in c#

We use the Northwind database to play demo. If you haven't got Northwind database, you can view How to download and restore Northwind database in SQL Server

Add an EF model to your project, then select Product table

entity framework database first

Step 3: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoCompleteTextBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Retrieve data from product table, then add to textbox
            using (NorthwindEntities db = new NorthwindEntities())
            {
                productBindingSource.DataSource = db.Products.ToList();
                AutoCompleteStringCollection ac = new AutoCompleteStringCollection();
                foreach (Product p in productBindingSource.DataSource as List<Product>)
                    ac.Add(p.ProductName);
                txtProductName.AutoCompleteCustomSource = ac;
            }
        }

        private void txtProductName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //Search data from textbox
                using (NorthwindEntities db = new NorthwindEntities())
                {
                    productBindingSource.DataSource = db.Products.Where(p => p.ProductName.Contains(txtProductName.Text)).ToList();
                }
            }
        }
    }
}

VIDEO TUTORIALS