How to connect an access database in C #

I have an access database file with 7 tables, but I don’t know how to connect and show all the tables. If anyone can help me?

this is my code but it shows nothing

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; 
+7
source share
2 answers

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(); } } 

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

+14
source

You create a DataGridView on the fly and set a DataSource for it. That's fine, but then you add a DataGridView to the layout collection's controls collection?

 this.Controls.Add(dataGridView1); 

By the way, the code is a little confused

 String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True"; string sql = "SELECT Clients FROM Tables"; using(OleDbConnection conn = new OleDbConnection(connection)) { conn.Open(); DataSet ds = new DataSet(); DataGridView dataGridView1 = new DataGridView(); using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn)) { adapter.Fill(ds); dataGridView1.DataSource = ds; // Of course, before addint the datagrid to the hosting form you need to // set position, location and other useful properties. // Why don't you create the DataGrid with the designer and use that instance instead? this.Controls.Add(dataGridView1); } } 

EDIT . After the comments below, it is clear that there is some confusion between the file name (TABLES.ACCDB) and the table name CLIENTS.
The SELECT statement is defined (in its basic form) as

  SELECT field_names_list FROM _tablename_ 

therefore, the correct syntax used to retrieve all client data,

  string sql = "SELECT * FROM Clients"; 

where * means β†’ all fields present in the table

+3
source

All Articles