Hi kana250688,
Please refer the below sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
Form Design
I have added a TextBox and a Label control to the Form.
The TextBox has been assigned with a TextChanged event handler.
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
AutoCompleteStringCollection acsCustomers = new AutoCompleteStringCollection();
foreach (DataRow dr in this.GetData().Rows)
{
acsCustomers.Add(dr["Name"].ToString());
}
txtCustomers.AutoCompleteMode = AutoCompleteMode.Suggest;
txtCustomers.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtCustomers.AutoCompleteCustomSource = acsCustomers;
}
private void txtCustomers_TextChanged(object sender, EventArgs e)
{
lblError.Hide();
DataRow[] rows = this.GetData().Select("Name='" + txtCustomers.Text.Trim() + "'");
if (rows.Length == 0)
{
lblError.Show();
}
}
private DataTable GetData()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT Name FROM Customers";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim acsCustomers As AutoCompleteStringCollection = New AutoCompleteStringCollection()
For Each dr As DataRow In Me.GetData().Rows
acsCustomers.Add(dr("Name").ToString())
Next
txtCustomers.AutoCompleteMode = AutoCompleteMode.Suggest
txtCustomers.AutoCompleteSource = AutoCompleteSource.CustomSource
txtCustomers.AutoCompleteCustomSource = acsCustomers
End Sub
Private Sub txtCustomers_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtCustomers.TextChanged
lblError.Hide()
Dim rows As DataRow() = Me.GetData().Select("Name='" & txtCustomers.Text.Trim() & "'")
If rows.Length = 0 Then
lblError.Show()
End If
End Sub
Private Function GetData() As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT Name FROM Customers"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query, con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
Screenshot