Oct 2, 2009

Autcomplete combobox in Windows Application

Introduction : Autcomplete combobox in Windows Application

This code demonstrates the use of AutoComplete combobox in Windows Application

Pre-requisites :

Combobox properties to be set for achieving this :
1) AutoComplete Mode - You can select any from it, either Suggest/Append/SuggestAppend (In my case I have taken Suggest here)
2) AutoCompleteSource - Set it as CustomSource
3) AutoCompleteCustomSource - Its a collection
















As shown in the Figure take a form with a combobox named cmbcity. Here I am fetching city from the database.

public partial class Form9 : Form

{
public string strConnection = ConfigurationManager.ConnectionStrings["test1"].ConnectionString;
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
public Form9()

{
InitializeComponent();
}
private void Form9_Load(object sender, EventArgs e)

{
OdbcDataReader dReader;
OdbcConnection conn = new
OdbcConnection();

conn.ConnectionString = strConnection;
OdbcCommand cmd = new OdbcCommand();

cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select distinct city sample order by city";

conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)

{
while (dReader.Read())
namesCollection.Add(dReader["city"].ToString());

}
else

{
MessageBox.Show("Data not found");

}
dReader.Close();
cmbcity.AutoCompleteMode = AutoCompleteMode.Suggest;
cmbcity.AutoCompleteSource = AutoCompleteSource.CustomSource;

cmbcity.AutoCompleteCustomSource = namesCollection;
}
}

No comments:

Post a Comment