How to Fill ComboBox with Data inside the DataGridView in C# and MS Access Database

This time, I will teach you how to fill combobox with data in the datagridview in C# and MS Access Database. This is very useful most especially when you are dealing with combo box and datagridview control. In this way, you can manipulate the data inside a combobox easily.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application in C#. psq1

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 for OLeDB to access OLeDB libraries.
  1. using System.Data.OleDb;

Step 4

Create a connection between the access database and c#. After that, declare all the classes that are needed.
  1.         OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "/studentdb.accdb");
  2.         OleDbCommand cmd;
  3.         OleDbDataAdapter da;
  4.         DataTable dt;
  5.         string sql;

Step 5

Create a method for adding the comboxbox column with data in the datagridview.
  1.  
  2.         private void fill_combo(string sql)
  3.         {
  4.             try
  5.             {
  6.                 con.Open();
  7.  
  8.                 cmd = new OleDbCommand();
  9.                 da = new OleDbDataAdapter();
  10.                 dt = new DataTable();
  11.                 DataGridViewComboBoxColumn cbo = new DataGridViewComboBoxColumn();
  12.  
  13.                 cmd.Connection = con;
  14.                 cmd.CommandText = sql;
  15.                 da.SelectCommand = cmd;
  16.                 da.Fill(dt);
  17.  
  18.                 cbo.HeaderText="Name";
  19.                 cbo.DataSource = dt;
  20.                 cbo.ValueMember = "ID";
  21.                 cbo.DisplayMember = "fname";
  22.  
  23.                 dataGridView1.Columns.Add(cbo);
  24.  
  25.             }
  26.             catch(Exception ex)
  27.             {
  28.                 MessageBox.Show(ex.Message);
  29.             }
  30.             finally
  31.             {
  32.                 con.Close();
  33.                 da.Dispose();
  34.             }
  35.         }

Step 6

Do the following codes to execute the method that you have created in the first load of the form.
  1.  
  2.         private void Form1_Load(object sender, EventArgs e)
  3.         {
  4.             sql = "Select * From tblstudent";
  5.             fill_combo(sql);
  6.         }
Download the complete sourcecode 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