Tuesday, August 11, 2009

How To: Create AutoComplete TextBox in Windows Application

in this article I'll show you how to create AutoComplete TextBox in Windows Application, and I'll Getting the Data from Database.

I'll will use MS Access file as a database.
so let's start !!

1- Create Windows Forms Application.
2- add TextBox Control.
3- copy the below code into your form.

AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection();

private void AutoCompleteTextBox()
{
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\Test.mdb");
string con = "select distinct Question from Questions order by Question asc ";
OleDbCommand aCommand = new OleDbCommand(con, aConnection);

aConnection.Open();
OleDbDataReader aReader = aCommand.ExecuteReader();

if (aReader.HasRows)
{
while (aReader.Read())
{
stringCollection.Add(aReader[0].ToString());
}
}

aReader.Close();
aConnection.Close();

textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteCustomSource = stringCollection;
}

private void Form1_Load(object sender, EventArgs e)
{
AutoCompleteTextBox();
}

2 comments:

  1. also you can use from property window - F4

    ReplyDelete
  2. How Can you do that for RichTextBox?
    Because richtextbox does not have a property like AutoCompleteMode.

    ReplyDelete