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