Now, in this tutorial, I’m going to teach you how to save multiple data in C# and MS Access Database. There are times that you are having a hard time on what to do with saving multiple data. Well, this tutorial is just right for you. This is just simple yet very helpful when you happened to encounter this kind of problem. All you have to do is follow all the instructions that are shown below.
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;
Establish a connection between the ms access database and c#. After that, declare a class and variable that is needed.
- OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + Application.StartupPath + "/studentdb.accdb");
- OleDbCommand cmd;
- string sql;
Create a method for saving data.
- private void Save_Data(string sql)
- cmd = new OleDbCommand();
- cmd.Connection = con;
- cmd.CommandText = sql;
- catch (Exception ex)
Do the following codes to execute the method that you have created in saving multiple data when the button is clicked.
- private void button1_Click(object sender, EventArgs e)
- for(int i = 0;i < dataGridView1.Rows.Count - 1; i++)
- sql = "INSERT INTO tblstudent (fname,lname) VALUES ('" + dataGridView1.Rows[i].Cells.Value + "','" + dataGridView1.Rows[i].Cells.Value + "')";
- MessageBox.Show("Data has been saved in the database.");
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.