This tutorial will show you how to set your textbox support autocomplete in DataGridView using C#.NET
As you see, AutoCompleteCustomSource, AutoCompleteMode and AutoCompleteSource properties to perform an auto-completion of a user's input strings by comparing the prefix letters entered with the prefix of all strings in the data source.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace CSharpCodeDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] row = new string[] { "1", "Product 1", "150" };
dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "200" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "350" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "400" };
dataGridView1.Rows.Add(row);
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
string title = dataGridView1.Columns[1].HeaderText;
if (title == "Product Name")
{
TextBox txt = e.Control as TextBox;
if (txt != null)
{
txt.AutoCompleteMode = AutoCompleteMode.Suggest;
txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection DataCollection = new AutoCompleteStringCollection();
//Add data source to textbox control
AddItems(DataCollection);
txt.AutoCompleteCustomSource = DataCollection;
}
}
}
public void AddItems(AutoCompleteStringCollection data)
{
data.Add("Product 1");
data.Add("Product 2");
data.Add("Product 3");
data.Add("Product 4");
}
}
}
Each time you click on the DataGridView in the Product Name column, the list of products is automatically populated allowing you to select the product