2016/07/08

C#.Net Connect Access 2007

程式碼:
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;

namespace TestProject
{
    public partial class Form1 : Form
    {
        private String text
        {
            get { return this.textBox1.Text; }
        }

        private readonly String sqlStr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}\Database1.accdb;Persist Security Info=False;" , Directory.GetCurrentDirectory());
        private OleDbConnection conn;
        private OleDbCommand cmd;

        public Form1()
        {
            InitializeComponent();
            DBinit();
        }

        private void DBinit() {
            conn = new OleDbConnection(sqlStr);
            conn.Open();
            string sql = "Select * from cyfang";
            cmd = new OleDbCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            dataGridView1.DataSource = table;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            conn.Close();
        }
    }
}

執行結果: