How to Create a Simple Search Based on RadioButton in C# and MySQL Database

In this tutorial, I will teach you how to create a simple search based on radiobutton using c# and mysql database. This method has the ability to select one option from a group that is used to control the data, then it will be displayed in the datagriview. Follow the step by step guide to see how it works.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Open the code editor by pressing the F7 on the keyboard. In the code editor, add a namespace to access MySQL Libraries.
  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. MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=profile;sslMode=none");
  2. MySqlCommand cmd;
  3. MySqlDataAdapter da;
  4. DataTable dt;
  5. string sql;

Step 5

Create a method for retrieving data in the database and it will be displayed inside the datagridview.
  1.  
  2. private void LoadData(string sql,DataGridView dtg)
  3. {
  4. try
  5. {
  6. con.Open();
  7.  
  8. cmd = new MySqlCommand();
  9. da = new MySqlDataAdapter();
  10. dt = new DataTable();
  11.  
  12. cmd.Connection = con;
  13. cmd.CommandText = sql;
  14.  
  15. da.SelectCommand = cmd;
  16. da.Fill(dt);
  17.  
  18. dtg.DataSource = dt;
  19.  
  20.  
  21. }
  22. catch(Exception ex)
  23. {
  24. MessageBox.Show(ex.Message);
  25. }
  26. finally
  27. {
  28. con.Close();
  29. da.Dispose();
  30. }
  31. }

Step 6

Write the following code for retrieving data in the database in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. sql = "SELECT * FROM `profile`";
  5. LoadData(sql, dataGridView1);
  6. }

Step 7

Write this code for finding data in the database.
  1.  
  2. private void rdoFemale_CheckedChanged(object sender, EventArgs e)
  3. {
  4. sql = "SELECT * FROM `profile` WHERE `gender`='" + rdoFemale.Text + "'";
  5. LoadData(sql, dataGridView1);
  6. }
  7. private void rdoMale_CheckedChanged(object sender, EventArgs e)
  8. {
  9. sql = "SELECT * FROM `profile` WHERE `gender`='" + rdoMale.Text + "'";
  10. LoadData(sql, dataGridView1);
  11. }
The complete source code is included, you 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.

Add new comment