AutoComplete ComboBox Control From Database

Rajesh081725
Posted by Rajesh081725 under C# category on | Points: 40 | Views : 3111
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(); }
}
}
}

Comments or Responses

Posted by: T.Saravanan on: 11/15/2012 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Rajesh,

What is Auto Complete ComboBox control and its uses? Can you explain?

Please post code inside the code tag.
Posted by: Rajesh081725 on: 12/7/2012 Level:Bronze | Status: [Member] | Points: 10
Hi Sarav,
If you are add list of item to drop down list at design time
Run time is load all list of item in drop down list
Auto complete main use of when u select a one letter ,that letter based list of item display in the list.
The Combobox won't look like a Textbox, but when it has focus, typing into it will auto-select the best match from the Items list.


Login to post response