ComboBox联动DataGridview之Access表名联动表内容
Access2003
工具 -> 选项 -> 视图 -> 勾选隐藏对象、系统对象
工具 -> 安全 -> 用户与组的权限->选择MSysObjects->勾选读取数据
Access2007
Office按钮->Access选项->当前数据库->导航选项->勾选显示系统对象->
数据库工具->用户和权限->用户与组权限->对象名称->选择MSysObjects->勾选读取数据
//将Access中的表名绑定到下拉框
private void Bind2ComboBox()
{
//Access2003连接字符串
string conStr = "Provider=Microsoft.Jet.OleDb.4.0;";
conStr += @"Data Source=D:\Assisment.mdb;";
conStr += "Jet OleDb:DataBase Password='123456';";
//创建数据库连接
OleDbConnection con = new OleDbConnection(conStr);
//查询access所有用户表名的查询语句
string sequal = "select id,name from MSysObjects where type=1 and flags = 0";
DataSet ds = new DataSet();
try
{
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(sequal, con);
oda.Fill(ds);
//将表名绑定到下拉框
this.comboBox1.DataSource = ds.Tables[0];
this.comboBox1.DisplayMember = "name";
this.comboBox1.ValueMember = "id";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
}
//下拉框选择变化事件
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string conStr = "Provider=Microsoft.Jet.OleDb.4.0;";
conStr += @"Data Source=D:\Assisment.mdb;";
conStr += "Jet OleDb:DataBase Password='123456';";
//创建数据库连接
OleDbConnection con = new OleDbConnection(conStr);
//解析下拉框选中的表名
string tableName = ((DataRowView)this.comboBox1.SelectedItem).Row.ItemArray[1].ToString();
//查询access所有用户表名的查询语句
string sequal = "select * from "+tableName+"";
DataSet ds = new DataSet();
try
{
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(sequal, con);
oda.Fill(ds);
//绑定表格
this.dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
}
code in my life.