How to make a TextBox AutoComplete in C#

By FoxLearn 7/16/2024 9:01:20 AM   8.26K
Making an auto complete TextBox using sql database in C# Windows Forms Application.

To create a TextBox AutoComplete feature in a C# WinForms application using data from a SQL database involves a few steps:

You need a database table that contains the data you want to use for autocomplete suggestions. I will 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

Next, Open your Visual Studio, then click 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

Drag and drop the Label, TextBox and DataGridView controls from your Visual Studio toolbox onto your form designer, then you can layout your form as shown below.

auto complete textbox in c#

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

entity framework database first

To fetch data to provide autocomplete suggestions in the TextBox control. We will use EF queries to fetch data from the database table.

Here's a basic outline of how you can achieve this:

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();
        }

        // Load data into DataTable
        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();
                }
            }
        }
    }
}

This code sets up an AutoComplete feature for a TextBox control in a WinForms application by fetching data from a SQL database and populating the AutoComplete suggestions accordingly.

VIDEO TUTORIAL