Multi Column Autocomplete ComboBox in C#

In this tutorial, I will teach you how to autocomplete a combobox with multiple columns in c#. This method has the ability to auto suggest and append a combobox with different columns from the datatable. See the procedure below.

Creating Database

Create a database named “test”. Create a table in the database that you have created.
  1. CREATE TABLE `tblperson` (
  2. `PersonID` int(11) NOT NULL,
  3. `Fname` varchar(90) NOT NULL,
  4. `Lname` varchar(90) NOT NULL,
  5. `Mname` varchar(90) NOT NULL
Insert the data in the table.
  1.  
  2. INSERT INTO `tblperson` (`PersonID`, `Fname`, `Lname`, `Mname`) VALUES
  3. (1, 'Janno', 'Palacios', 'E'),
  4. (2, 'John Craig', 'Nillos', 'P');

Creating Application.

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application. auto12

Step 2

Add a ComboBox in the form. auto213

Step 3

Double click the form to fire the code view and add the following code for your imports to access MySQL library.
  1. using MySql.Data.MySqlClient;

Step 4

Create a connection between C# and MySQL database. After that, declare all the classes that are needed.
  1.  
  2. MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=janobe;database=test;sslMode=none");
  3. MySqlCommand cmd;
  4. MySqlDataAdapter da;
  5. DataTable dt;
  6. string sql;

Step 5

Create a method for autocomplete combobox.
  1. public void autocomplete()
  2. {
  3. try
  4. {
  5. sql = "SELECT * FROM tblperson";
  6. con.Open();
  7. cmd = new MySqlCommand();
  8. cmd.Connection = con;
  9. cmd.CommandText = sql;
  10. da = new MySqlDataAdapter();
  11. da.SelectCommand = cmd;
  12. dt = new DataTable();
  13. da.Fill(dt);
  14.  
  15. int maxcolumn = dt.Columns.Count - 1;
  16.  
  17. foreach(DataRow row in dt.Rows)
  18. {
  19. for (int i = 0; i < maxcolumn; i++)
  20. {
  21. comboBox1.AutoCompleteCustomSource.Add(row.Field<string>("Fname"));
  22. comboBox1.AutoCompleteCustomSource.Add(row.Field<string>("Lname"));
  23. comboBox1.AutoCompleteCustomSource.Add(row.Field<string>("Mname"));
  24. }
  25.  
  26. }
  27.  
  28.  
  29. }

Step 6

Call the method that you have created and set it in the first load of the form.
  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3. autocomplete();
  4. }
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT FB Account – https://www.facebook.com/onnaj.soicalap

Add new comment