Clever Way to Save Multiple Data Using C# and MS Access Database
Submitted by janobe on Tuesday, April 30, 2019 - 17:11.
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.
Download the complete source code 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
Creating an Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application in C#.Step 2
Do the form just like shown below.Step 3
Press F7 to open the code editor. In the code editor, add a namespace forOLeDB
to access OLeDB
libraries.
- using System.Data.OleDb;
Step 4
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;
Step 5
Create a method for saving data.- private void Save_Data(string sql)
- {
- try
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- cmd.ExecuteNonQuery();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- }
- }
Step 6
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[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "')";
- Save_Data(sql);
- }
- MessageBox.Show("Data has been saved in the database.");
- }
Add new comment
- 436 views