Simple Search Based on Two Columns in C# and MySQL Database
Submitted by janobe on Monday, March 18, 2019 - 09:25.
In this tutorial, I will teach you how to create a simple search based on two columns in c# and MySQL database. This program will illustrate how to search for data or records in the database based on two fields in the table. It has an automatic search for data in the database that will be displayed into the datagridview. Let’s begin.
The complete source code is included, yo can download it 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 for c#.
Step 2
Do the form just like shown below.
Step 3
Open the code editor by pressing the F7 on the keyboard. In the code editor, add a namespace to access MySQL Libraries.- using MySql.Data.MySqlClient;
Step 4
Create a connection between C# and MySQL Database. After that, declare all the classes that are needed.- MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=dbsubjects;sslMode=none");
- MySqlCommand cmd;
- MySqlDataAdapter da;
- DataTable dt;
- string sql;
Step 5
Create a method for retrieving data in the database.- public void simple_search(string sql,DataGridView dtg)
- {
- try
- {
- con.Open();
- cmd = new MySqlCommand();
- da = new MySqlDataAdapter();
- dt = new DataTable();
- 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 6
Double click the form and do the following codes for retrieving data in the database in the first load of the form.- private void Form1_Load(object sender, EventArgs e)
- {
- sql = "SELECT `SUBJ_ID` as 'ID', `SUBJ_CODE` as 'CODE', `SUBJ_DESCRIPTION` as 'DESCRIPTION', `UNIT`, `PRE_REQUISITE` AS 'PRE-REQUISITE' FROM `subject` WHERE `SUBJ_CODE` LIKE '%" + textBox1.Text + "%' OR `SUBJ_DESCRIPTION` LIKE '%" + textBox1.Text + "%'";
- simple_search(sql, dataGridView1);
- }
Step 7
Write this code for searching data in the database.- private void textBox1_TextChanged(object sender, EventArgs e)
- {
- sql = "SELECT `SUBJ_ID` as 'ID', `SUBJ_CODE` as 'CODE', `SUBJ_DESCRIPTION` as 'DESCRIPTION', `UNIT`, `PRE_REQUISITE` AS 'PRE-REQUISITE' FROM `subject` WHERE `SUBJ_CODE` LIKE '%" + textBox1 .Text + "%' OR `SUBJ_DESCRIPTION` LIKE '%" + textBox1.Text + "%'";
- simple_search(sql, dataGridView1);
- }
Add new comment
- 289 views