Home > DeveloperSection > Forums > How to connect access database in c#
Dag Hammarskjold
Dag Hammarskjold

Total Post:24

Points:168
Posted on    June-19-2013 2:56 AM

 ADO.Net ADO.Net 
Ratings:


 2 Reply(s)
 2263  View(s)
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.


Dev Patel

Total Post:26

Points:182
Posted on    June-19-2013 8:24 AM

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.

Manmohan Jha

Total Post:35

Points:245
Posted on    July-25-2013 12:54 AM

          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

Don't want to miss updates? Please click the below button!

Follow MindStick