1、打开指定的Access表
首先在全局变量中定义Access的连接对象,如下:
private OleDbConnection accessOledbConnection;
然后在按钮“打开Access文件button”的Click事件中添加如下代码:
private void 打开Access文件button_Click(object sender, EventArgs e)
{
OpenFileDialog openDG = new OpenFileDialog();
openDG.Title = "打开Access数据库";
openDG.Filter = "Access数据库(*.mdb)|*.mdb|所有文件(*.*)|*.*";
openDG.ShowDialog();
string filename;
filename = openDG.FileName;
DataTable table = new DataTable();
string strConn
= @"
rovider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";";
accessOledbConnection = new OleDbConnection(strConn);
accessOledbConnection.Open();
table = accessOledbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
AccessComboBox.Items.Clear();
foreach (DataRow dr in table.Rows)
{
AccessComboBox.Items.Add((String)dr["TABLE_NAME"]);
}
AccessComboBox.Text = AccessComboBox.Items[0].ToString();
}
2、打开指定的Access表
在按钮“打开指定的Access表button”的Click事件中添加如下代码:
private void 打开指定的Access表button_Click(object sender, EventArgs e)
{
OleDbCommand oleDbCommand = accessOledbConnection.CreateCommand();
oleDbCommand.CommandText = @"SELECT * FROM " + AccessComboBox.Text;
DataTable table = new DataTable();
DataRow dr;
OleDbDataReader odrReader = oleDbCommand.ExecuteReader();
//查询并显示数据
int size = odrReader.FieldCount;
for (int i = 0; i < size; i++)
{
DataColumn dc;
dc = new DataColumn(odrReader.GetName(i));
table.Columns.Add(dc);
}
while (odrReader.Read())
{
dr = table.NewRow();
for (int i = 0; i < size; i++)
{
dr[odrReader.GetName(i)] = odrReader[odrReader.GetName(i)].ToString();
}
table.Rows.Add(dr);
}
//关闭连接
odrReader.Close();
//oledbcConnection.Close();
dataGridView1.DataSource = table;
}
其结果如下图所示: