Adding AutoComplete Functionality to a TextBox Control using C#.Net



Hello Friends !!

Today I am writing my first C#.Net Article going a bit out of my way from SQL and MSBI.

This is something related to a requirement which comes my way when in a windows Application i need to give a drop down for all like customer names when typing the names in the Text Box as a very basic user friendly option.

Here is how we can do this -
Let's take as assumption as we have a table in SQL as CustomerTable and we want to take the FirstName of the Customer as our search result.

we will write this code in the Form load event of the form which contains the Text box.

The connectionStringName will be configured and can be get from the App.Config table.

Also you need to change the below 2 properties of the Text Box on which you want to implement the Auto Complete functionality.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FirstName FROM CustomerTable", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
   {
        MyCollection.Add(reader.GetString(0));
   }
txtFirstName.AutoCompleteCustomSource = MyCollection;
con.Close();

This will automatically get refreshed as when we loads the form after any changes in the DB.

Happy Coding !!

Comments

Popular posts from this blog

SSIS vs. T-SQL

Sync SSAS Cube From One Environment to Another

SQL Function to replace special characters from a string