Hi PRA,
Use TextBox control and set the below properties to work as AutoComplete.
1. AutoCompleteMode - Gets or sets an option that controls how automatic completion works.
2. AutoCompleteSource - Gets or sets a value specifying the source of complete strings used for automatic completion.
3. AutoCompleteCustomSource - Gets or sets a custom StringCollection to set the CustomSource.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
C#
using System.Data.SqlClient;
VB.Net
Imports System.Data.SqlClient
Code
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string conString = @"Data Source =.; Initial Catalog = Northwind; UID=sa;PWD=12345";
string query = "SELECT DISTINCT ContactName FROM Customers";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
AutoCompleteStringCollection autoCompleteStringCollection = new AutoCompleteStringCollection();
while (sdr.Read())
{
autoCompleteStringCollection.Add(sdr["ContactName"].ToString());
}
txtName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = autoCompleteStringCollection;
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
MessageBox.Show("Customer Name : " + txtName.Text.Trim());
}
}
VB.Net
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conString As String = "Data Source =.; Initial Catalog = Northwind; UID=sa;PWD=12345"
Dim query As String = "SELECT DISTINCT ContactName FROM Customers"
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(conString)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
Dim autoCompleteStringCollection As AutoCompleteStringCollection = New AutoCompleteStringCollection()
While sdr.Read()
autoCompleteStringCollection.Add(sdr("ContactName").ToString())
End While
txtName.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource
txtName.AutoCompleteCustomSource = autoCompleteStringCollection
End Using
End Using
End Sub
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
MessageBox.Show("Customer Name : " & txtName.Text.Trim())
End Sub
End Class
Screenshot