blog

Home / DeveloperSection / Blogs / Text Box Auto Complete Feature

Text Box Auto Complete Feature

Shankar M4777 12-Feb-2013

Unlike List Box control we can achieve AutoComplete Text Feature in Textbox. In this blog I have discussed how to achieve Autosuggest Feature of Textbox in Windows Forms.

1. Place a Textbox Control on to the Form.

2. Write the code in the Form Loads Event

private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection conn;
            SqlCommand cmd;
            string ConnectionString = @"Data Source = L04WSCHE0471\SQLEXPRESS;Initial Catalog = ORCD;User id =yourdbUserName; Password =yourPassword; Integrated Security = True";
            string CommandString = "SELECT ENAME FROM EMP";
 
            using (conn = new SqlConnection(ConnectionString))
            {
               cmd = new SqlCommand(CommandString, conn);
               conn.Open();
               SqlDataReader myReader = cmd.ExecuteReader();
               AutoCompleteStringCollection Collection = new AutoCompleteStringCollection();
               while (myReader.Read())
               {
                   Collection.Add(myReader["ENAME"].ToString());
               }
               textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
               textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
               textBox1.AutoCompleteCustomSource = Collection;
            }
        }

Here, we create an instance of SqlConnection and SqlCommand Class. Then, we pass the SqlCommand Class the SQL Statement.

Once the connection is opened based on the command passed, we create a DataReader.

Note, that the DataReader requires a live connection to the database.

 

To read the data from the database, we Iterate using the myReader.Read () method. After the AutoCompleteStringCollection object is built we assign it to the textbox AutoCompleteCustomSource property which is set to enumeration AutoCompleteSource.CustomSource. The textbox AutoCompleteMode property is set to enumeration AutoCompleteMode.SuggestAppend.

 Text Box Auto Complete Feature

Thanks for reading..


Leave Comment

Comments

Liked By