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.
Open Microsoft Visual Studio 2015 and create a new windows form application in C#.
Do the form just like shown below.
Press F7 to open the code editor. In the code editor, add a namespace for
OLeDB to access
- using System.Data.OleDb;
Create a connection between the access database and c#. After that, declare all the classes that are needed.
- OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "/studentdb.accdb");
- OleDbCommand cmd;
- OleDbDataAdapter da;
- DataTable dt;
- string sql;
Create a method for adding the comboxbox column with data in the datagridview.
- private void fill_combo(string sql)
- cmd = new OleDbCommand();
- da = new OleDbDataAdapter();
- dt = new DataTable();
- DataGridViewComboBoxColumn cbo = new DataGridViewComboBoxColumn();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- cbo.DataSource = dt;
- cbo.ValueMember = "ID";
- cbo.DisplayMember = "fname";
- catch(Exception ex)
Do the following codes to execute the method that you have created in the first load of the form.
- private void Form1_Load(object sender, EventArgs e)
- sql = "Select * From tblstudent";
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.