C Sharp And Ms Access Database Tutorial 4 How To Connect To Ms Access Database In C Sharp

C# And Ms Access Database Tutorial #4 – How To Connect To Ms Access Database In C#

How To Connect To Ms Access Database In C#

This tutorial Shows How To Connect To Microsoft Access Database In C# Using Visual Studio 2010.


First create connection string field. The connection string can be obtained from the connected database properties. This was shown in the previous tutorial. Get The connection string and assign it to a string variable.
Then create OLE DB Connection field.
Then initialize OLE DB Connection field in the constructor.
Instantiating OLE DB Connection inside form1 constructor. This means that OLE DB connection instance is created automatically once the form loads since its inside the constructor. Constructor is called automatically when an object of a class is created. Now put Microsoft access database connection string as an argument.

How To Connect To Ms Access Database In C#
How To Connect To Ms Access Database In C#
How To Connect To Ms Access Database In C Sharp - Connection Open
How To Connect To Ms Access Database In C Sharp – Connection Open
How To Connect To Ms Access Database In C Sharp - Connection Closed
How To Connect To Ms Access Database In C Sharp – Connection Closed

C# SOURCE CODE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace CSharpAndMicrosoftAccessDatabaseCRUD
{
    public partial class Form1 : Form
    {

        String microsoftAccessDatabaseConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Authentic\Documents\MicrosoftAccessDatabase.accdb";
        public OleDbConnection microsoftAccessDatabaseOleDbConnection = null;
        public Form1()
        {
            // Initializing oledb connection inside a constructor
            microsoftAccessDatabaseOleDbConnection = new OleDbConnection(microsoftAccessDatabaseConnectionString);
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //Open connection
            if (microsoftAccessDatabaseOleDbConnection.State == ConnectionState.Closed)
            {
                microsoftAccessDatabaseOleDbConnection.Open();
                MessageBox.Show("Connection Open........");
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Close connection
            if (microsoftAccessDatabaseOleDbConnection.State == ConnectionState.Open)
            {
                microsoftAccessDatabaseOleDbConnection.Close();
                MessageBox.Show("Connection Closed........");
            }
        }

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *