Fill Data Based on DataGridViewComboBoxColumn in C# and MySQL Database

In this tutorial, I will teach you how to fill the data in the DataGridViewComboBoxColumn using C# and MySQL database. This method has the ability to add a combobox column in the datagridview. It also has the capacity to fill the combobox with data from the database. This method is very useful when you are dealing with datagridview control.

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

Press F7 to open the code editor. In the code editor, add a namespace to access MySQL libraries
  1.  
  2. using MySql.Data.MySqlClient;

Step 4

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

Step 5

Create a method for adding and filling data in the combobox.
  1.  
  2. private void fill_combo(string sql)
  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. foreach (DataRow dr in dt.Rows)
  19. {
  20. cbo.Items.Add(dr.Field<string>("SUBJ_CODE"));
  21. cbo.Name = "Subject Code";
  22. }
  23. //add the combobox in the column in the datagridview
  24. dataGridView1.Columns.Add(cbo);
  25. }
  26. catch(Exception ex)
  27. {
  28. MessageBox.Show(ex.ToString());
  29. }
  30. finally
  31. {
  32. con.Close();
  33. da.Dispose();
  34. }
  35.  
  36. }

Step 6

Writ the following codes to execute the method in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. sql = "SELECT * FROM subject";
  5. fill_combo(sql);
  6. }
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