Connecting C# Application To MS Access Database

This is my first article for the beginners of the C# Programming. Here in this article, I will show you how to connect a C# application with MS Access 2013, 2016 or Office 365 database.

Open MS Access, click on a Blank Desktop Database, since I have Office 365 so it will look like the following screenshot,

 

Now you can give any name to the database and then click Create.

Now create a Table in database, You can name a table anything you want, here I named it "Student" . There are three columns in the table ID, FirstName and LastName like the following,

 

Now open Visual Studio, start a new Windows Form Application and give any name you want. Now Drag and Drop database file from the Documents to the Project Directory folder in Solution Explore which we created with MS Access. Design the form like the following,

 

Double Click on the Submit Button.

Write a Namespace for connectivity as in the following code snippet:
  1. using System.Data.OleDb;  


Now get a connection string, Go to Tools menu and select connect to the database and browse database from the Project Directory.

 

Click on Advanced and copy the highlighted text as your connection string.

 

Now make connection using the following code:  
  1. OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=testapp.accdb");  
And write the following code:
  1. OleDbCommand cmd = con.CreateCommand();    
  2.     con.Open();    
  3.     cmd.CommandText = "Insert into Student(FirstName,LastName)Values('" + textBox1.Text + "','" + textBox2.Text + "')";    
  4.     cmd.Connection = con;    
  5.     cmd.ExecuteNonQuery();    
  6.     MessageBox.Show("Record Submitted","Congrats");    
  7.     con.Close();   
 
  

Now you are all set to run your application. Keep coding!