In this article, we will learn how to create an AutoCompleteTextBox using a C# Windows Forms application. In my previous article, we learned
How to Search Records in DataGridView Using C#.
Let's begin.
Create a new Windows Forms application.
Drop a Label and TextBox control from the ToolBox.
Now go to the Code Behind file (.cs code) and add the following lines of code:
- using System;
- using System.Windows.Forms;
-
- namespace AutoCompleteTextBoxDemo
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void autoCompleteData()
- {
-
- txt_StateName.AutoCompleteSource = AutoCompleteSource.CustomSource;
-
- txt_StateName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
- txt_StateName.AutoCompleteCustomSource.AddRange(new string[]{"Maharastra","Andhra Pradesh","Assam","Punjab","Arunachal
-
- Pradesh","Bihar","Goa","Gujarat","Haryana"});
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- autoCompleteData();
- }
- }
- }
In the preceding code, we set the AutoCompleteSource, AutoCompleteMode and AutoCompleteCustomSource properties of the TextBox named txt_StateName so that it automatically completes the input string.
Preview
AutoComplete TextBox with Database:In this example, we will Suggest/Append the data in the TextBox (txt_StateName) from the database. For demonstration, I have created a database (named Sample). Add a Table, tbl_State. The following is the table schema for creating tbl_State.
Add the following lines of code:
- using System;
- using System.Windows.Forms;
- using System.Data.SqlClient;
-
- namespace AutoCompleteTextBoxDemo
- {
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- }
- private void autoCompleteData()
- {
- SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
- SqlCommand com = new SqlCommand("Select State from tbl_State", con);
- con.Open();
- SqlDataReader rdr = com.ExecuteReader();
-
- AutoCompleteStringCollection autoCompleteCollection = new AutoCompleteStringCollection();
- while (rdr.Read())
- {
- autoCompleteCollection.Add(rdr.GetString(0));
- }
-
- txt_StateName.AutoCompleteSource = AutoCompleteSource.CustomSource;
-
- txt_StateName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
- txt_StateName.AutoCompleteCustomSource = autoCompleteCollection;
- con.Close();
- }
-
- private void Form2_Load(object sender, EventArgs e)
- {
- autoCompleteData();
- }
- }
- }
Preview
I hope you like it. Thanks.