2014年2月12日 星期三

C# DataGridView 連接ACCESS with SQL語法

如何使用DataGridView連接ACCESS,使用簡單的SQL語法

使用到的物件
1. DataSet
2. OleDbDataAdapter 用來填入 DataSet 並更新資料來源

變數
strDatabase:Access檔案名稱
strsql: Connection String
strTableName:要讀取的Table Name

//OLE Naming Space
using System.Data.OleDb;

namespace DataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strDatabase = "C:\\FileDataBase.mdb";
            string strsql = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDatabase;
            string strTableName="TestTable";
            DataSet ds=new DataSet();
            OleDbDataAdapter oda;
            string strDataTable = "select * from " + strTableName;
            oda = new OleDbDataAdapter(strDataTable, strsql);
            oda.Fill(ds, strTableName);
            dataGridView1.DataSource = ds.Tables[strTableName];

        }
    }
}
Sample Code Download

沒有留言:

張貼留言