C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Autocomplete_controls_csharp
{
public partial class Form1 : Form
{
private string connStr = @"data source=.\sqlexpress;database=northwind;integrated security=true";
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Configure_ComboBox();
}
void Configure_ComboBox()
{
this.Connect();
if (dt == null)
{
MessageBox.Show("Error in Quering");
return;
}
IList<string> lstFirst = new List<string>();
IList<string> lstLast = new List<string>();
foreach (DataRow row in dt.Rows)
{
lstFirst.Add(row.Field<string>("firstname"));
lstLast.Add(row.Field<string>("lastname"));
}
this.comboBoxFirstName.Items.AddRange(lstFirst.ToArray<string>());
this.comboBoxFirstName.AutoCompleteMode = AutoCompleteMode.Suggest;
this.comboBoxFirstName.AutoCompleteSource = AutoCompleteSource.ListItems;
this.comboBoxLastName.Items.AddRange(lstLast.ToArray<string>());
this.comboBoxLastName.AutoCompleteMode = AutoCompleteMode.Suggest;
this.comboBoxLastName.AutoCompleteSource = AutoCompleteSource.ListItems;
}
void Connect()
{
SqlConnection conn = new SqlConnection(this.connStr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(@"select firstname,lastname from employees", conn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
dt = new DataTable();
ada.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message.ToString());
}
finally { conn.Close(); }
}
}
}
Visual Basic
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private connStr As String = "data source=.\sqlexpress;database=northwind;integrated security=true"
Dim dt As DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Configure_ComboBox()
End Sub
Sub Configure_ComboBox()
Me.Connect()
If dt Is Nothing Then
MessageBox.Show("Error in Quering")
Exit Sub
End If
Dim lstFirst As IList(Of String) = New List(Of String)
Dim lstLast As IList(Of String) = New List(Of String)
For Each _row As DataRow In dt.Rows
lstFirst.Add(_row("firstname"))
lstLast.Add(_row("lastname"))
Next
Me.ComboBoxFirstName.Items.AddRange(lstFirst.ToArray)
Me.ComboBoxFirstName.AutoCompleteMode = AutoCompleteMode.Suggest
Me.ComboBoxFirstName.AutoCompleteSource = AutoCompleteSource.ListItems
Me.ComboBoxLastName.Items.AddRange(lstLast.ToArray)
Me.ComboBoxLastName.AutoCompleteMode = AutoCompleteMode.Suggest
Me.ComboBoxLastName.AutoCompleteSource = AutoCompleteSource.ListItems
End Sub
Sub Connect()
Dim conn As New SqlConnection(connStr)
Try
conn.Open()
Dim cmd As New SqlCommand("select firstname,lastname from employees", conn)
Dim ada As New SqlDataAdapter(cmd)
dt = New DataTable
ada.Fill(dt)
Catch ex As Exception
MessageBox.Show("Error:" & ex.ToString)
Finally
conn.Close()
End Try
End Sub
End Class