HOW TO CONNECT ACCESS DATABASE IN C#

Dag Hammarskjold

Total Post:24

Points:168
Posted by  Dag Hammarskjold
 2853  View(s)
Ratings:
Rate this:
Hi Developers,

I have access database file with 7 tables in it but I don't know how to connect and show all tables, If some one can help me?

this is my code but it doesn't show anything

private void button1_Click(object sender, EventArgs e)
{
    OleDbConnection conn = new OleDbConnection();
    String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
    string sql  = "SELECT Clients  FROM Tables";
    conn.ConnectionString = connection;
    conn.Open();
    DataSet ds = new DataSet();
    DataGridView dataGridView1 = new DataGridView();
    BindingSource bSource = new BindingSource();
    OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn);
    adapter.Fill(ds);
    //conn.Close();                              
    dataGridView1.DataSource = ds;


Your help is greatly appreciated.
  1. Dev Patel

    Post:26

    Points:182
    Re: How to connect access database in c#

    Hi,


    Try this code,

    public void ConnectToAccess()
    {
        System.Data.OleDb.OleDbConnection conn = new 
            System.Data.OleDb.OleDbConnection();
        // TODO: Modify the connection string and include any
        // additional required properties for your database.
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            @"Data source= C:\Documents and Settings\username\" +
            @"My Documents\AccessFile.mdb";
        try
        {
            conn.Open();
            // Insert code to process data.
        }
            catch (Exception ex)
        {
            MessageBox.Show("Failed to connect to data source");
        }
        finally
        {
            conn.Close();
        }
    }

    I hope it helpful for you.

  1. Manmohan Jha

    Post:35

    Points:245
    Re: How to connect access database in c#

              Using MS Access 2007
              My database file in:-
              MyProject/bin/Debug


               private void btnSave_Click(object sender, EventArgs e)
               {
                OleDbConnection con = new OleDbConnection();
                con.ConnectionString =@"provider= Microsoft.ACE.OLEDb.12.0; Data Source =" + Application.StartupPath + "\\Db_School.accdb; Jet OLEDB:Database Password=Password";
                con.Open();
                OleDbCommand cmd = new OleDbCommand("SELECT Clients  FROM Tables", con);
                DataGridView dataGridView1 = new DataGridView();
                DataTable dt = new DataTable();
                OleDbDataReader dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();                               
                dataGridView1.DataSource = dt;
               }
    Mj

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!