This article is about Filter Combobox Datasource in C#. C# controls are located in the Toolbox of the development environment, and you use them to create objects on a form with a simple series of mouse clicks and dragging motions. Filter combobox using C# can display a text box combined with a ListBox, which enables the user to select items from the list or enter a new value. In this tutorial, you will learn in detail how to filter data that will display to atextbox and datagridview. We can use Event Combobox SelectedIndexChanged to complete this tutorial.
Combobox SelectedIndexChanged event
The SelectedIndexChanged event of a combobox fires when you change the selected item in a combobox. If you want to do something when you change the selection, you can write the program on the SelectedIndexChanged event. From the following code you can understand how to set values in the SelectedIndexChanged event of a combobox.
This tutorial uses Mysql for connecting the database and binding data. Follow this step to see how filtering data will display to Textbox and Datagridview.
- Create a new application project. In Visual Studio, on the menu click File> New > Project. For more details, see the following menu on the display.
- Then the New Project window will appear.
- Write down the name of the project that will be created on a field name. Specify the directory storage project by accessing the field location. Next, give the name of the solution in the Solution Name. Then click OK.
Create a new class for connecting database to Mysql and write the following program listing:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using MySql.Data.MySqlClient;
- using System.Windows.Forms;
- using System.Data;
-
- namespace Filter_Combobox
- {
- class ConnectionDB
- {
-
- MySql.Data.MySqlClient.MySqlConnection conn;
- string myConnectionString;
- static string host = "localhost";
- static string database = "test";
- static string userDB = "ecco";
- static string password = "password";
- public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
-
-
- public bool Open()
- {
- try
- {
- strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
- conn = new MySqlConnection(strProvider);
- conn.Open();
- return true;
- }
- catch (Exception er)
- {
- MessageBox.Show("Connection Error ! " + er.Message, "Information");
- }
- return false;
- }
-
- public void Close()
- {
- conn.Close();
- conn.Dispose();
- }
-
- public DataSet ExecuteDataSet(string sql)
- {
- try
- {
- DataSet ds = new DataSet();
- MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
- da.Fill(ds, "result");
- return ds;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return null;
- }
-
- public MySqlDataReader ExecuteReader(string sql)
- {
- try
- {
- MySqlDataReader reader;
- MySqlCommand cmd = new MySqlCommand(sql, conn);
- reader = cmd.ExecuteReader();
- return reader;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return null;
- }
-
- public int ExecuteNonQuery(string sql)
- {
- try
- {
- int affected;
- MySqlTransaction mytransaction = conn.BeginTransaction();
- MySqlCommand cmd = conn.CreateCommand();
- cmd.CommandText = sql;
- affected = cmd.ExecuteNonQuery();
- mytransaction.Commit();
- return affected;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return -1;
- }
- }
- }
- Create textbox, combobox, label properties in a windows form like below.
- Create Datagridview with properties like below.
Next step, BGo back to Windows form and view the code to write the following program listing,
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using MySql.Data.MySqlClient;
- using System.Data;
- using System.Collections;
-
- namespace Filter_Combobox
- {
- public partial class Form1 : Form
- {
- ConnectionDB con = new ConnectionDB();
-
-
- private static ArrayList ListID = new ArrayList();
- private static ArrayList ListFirstname = new ArrayList();
- private static ArrayList ListLastname = new ArrayList();
- private static ArrayList ListTelephone = new ArrayList();
- private static ArrayList ListAddress = new ArrayList();
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void getDataComboBox()
- {
- con.Open();
- string query = "select firstname from user";
- MySqlDataReader row;
- row = con.ExecuteReader(query);
- if (row.HasRows)
- {
- while (row.Read())
- {
- comboBox1.Items.Add(row["firstname"].ToString());
- }
-
- }
- con.Close();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- getDataComboBox();
- GetData();
- if (ListID.Count > 0)
- {
- updateDatagrid();
- }
- }
-
- private void GetData()
- {
- try
- {
- con.Open();
- string query = "select id,firstname,lastname,telephone,address from user";
-
-
- MySqlDataReader row;
- row = con.ExecuteReader(query);
- if (row.HasRows)
- {
- while (row.Read())
- {
- ListID.Add(row["id"].ToString());
- ListFirstname.Add(row["firstname"].ToString());
- ListLastname.Add(row["lastname"].ToString());
- ListTelephone.Add(row["telephone"].ToString());
- ListAddress.Add(row["address"].ToString());
- }
- }
- else
- {
- MessageBox.Show("Data not found");
- }
-
- con.Close();
- }
- catch (Exception err)
- {
- MessageBox.Show(err.ToString());
- }
-
- }
-
- private void updateDatagrid()
- {
- dataGridView1.Rows.Clear();
- for (int i = 0; i < ListID.Count; i++)
- {
- DataGridViewRow newRow = new DataGridViewRow();
-
- newRow.CreateCells(dataGridView1);
- newRow.Cells[0].Value = ListID[i];
- newRow.Cells[1].Value = ListFirstname[i];
- newRow.Cells[2].Value = ListLastname[i];
- newRow.Cells[3].Value = ListTelephone[i];
- newRow.Cells[4].Value = ListAddress[i];
- dataGridView1.Rows.Add(newRow);
- }
- }
-
- private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
- {
- try
- {
- if (comboBox1.SelectedItem.ToString() == "ALL")
- {
- clearData();
- GetData();
- if (ListID.Count > 0)
- {
- updateDatagrid();
- }
- }
- else
- {
- clearData();
- con.Open();
- string query = "select id,firstname,lastname,telephone,address from user where firstname = '" + comboBox1.SelectedItem.ToString() + "'";
-
-
- MySqlDataReader row;
- row = con.ExecuteReader(query);
- if (row.HasRows)
- {
- while (row.Read())
- {
- ListID.Add(row["id"].ToString());
- ListFirstname.Add(row["firstname"].ToString());
- ListLastname.Add(row["lastname"].ToString());
- ListTelephone.Add(row["telephone"].ToString());
- ListAddress.Add(row["address"].ToString());
- }
-
- textBox2.Text = row["telephone"].ToString();
- textBox3.Text = row["address"].ToString();
- updateDatagrid();
- }
- else
- {
- MessageBox.Show("Data not found");
- }
-
- con.Close();
- }
- }
- catch (Exception err)
- {
- MessageBox.Show(err.ToString());
- }
- }
-
- private void clearData()
- {
- ListID.Clear();
- ListFirstname.Clear();
- ListLastname.Clear();
- ListAddress.Clear();
- ListTelephone.Clear();
- textBox2.Text = "";
- textBox3.Text = "";
- }
- }
- }
- After you write down the program listings, press the F5 key to run the program and if you successfully connect your database the result is:
We have explained how to make a Filter Combobox Datasource program in C#, for those of you who want to download the source code of the program you can also do that. Hopefully this discussion is helpful to you.
You can see Filter Combobox Datasource C# from Github project in
Here.