How to Find Records Using an Autocomplete TextBox in C#.
Submitted by janobe on Monday, April 29, 2019 - 21:15.
In this tutorial, I will teach you how to find records using an autocomplete textbox in c#. This method has the ability to find records immediately by typing the data in the textbox . It also has the capability to auto-suggest and appends if there is an existing name in the database that you type in the textbox. Lets begin.
Download the complete source code and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in C#.
Step 2
Do the form just like shown below.
Step 3
Press F7 to open the code editor. In the code editor, add a namespace forOLeDB
to access OLeDB
libraries.
- using System.Data.OleDb;
Step 4
Create a connection between access database and c#. After that, declare all the classes that are needed.- OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "/studentdb.accdb");
- OleDbCommand cmd;
- OleDbDataAdapter da;
- DataTable dt;
- string sql;
Step 5
Create a method for autocomplete textbox.- private void autocomplete_texbox(string sql,TextBox txt)
- {
- try
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- da.Fill(dt);
- txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
- txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
- txt.AutoCompleteCustomSource.Clear();
- foreach(DataRow r in dt.Rows)
- {
- txt.AutoCompleteCustomSource.Add(r.Field<string>("Fname"));
- }
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 6
Create a method for searching data.- private void find_Records(string sql,DataGridView dtg)
- {
- try
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- da.Fill(dt);
- dtg.DataSource = dt;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 7
Do the following code to execute the autocomplete in a textbox method in the first load of the form.- private void Form1_Load(object sender, EventArgs e)
- {
- sql = "Select * From tblstudent";
- autocomplete_texbox(sql, textBox1);
- }
Step 8
Do the following code to execute the searching of data method.- private void textBox1_TextChanged(object sender, EventArgs e)
- {
- sql = "Select * FROM tblstudent WHERE Fname Like '%" + textBox1.Text + "%'";
- find_Records(sql, dataGridView1);
- }
Add new comment
- 285 views