我想在comboBox1里读取access里的数据,想实现数据库改变时,comboBox1也作出相应改变。就是控件与数据库绑定,实现实时刷新?用哪一个指令呀??请帮帮忙,谢谢啦!
参考:http://blog.csdn.net/stamina88/article/details/5317303
可以参考以下代码
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select oper_cod, oper_nam from dept",con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "dept_nam";
comboBox1.ValueMember = "dept_cod";
如果要实时刷新,可以用timer事件定时来刷新
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from department",con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "departmentId";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex>-1)
{
DataRowView drv = (DataRowView)comboBox1.SelectedItem;
int id = Convert.ToInt32(drv.Row["departmentId"].ToString());
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from major where departmentId='" + id + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
comboBox2.DataSource = dt;
comboBox2.DisplayMember = "major";
comboBox2.ValueMember = "majorId";
}
}
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection( @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\000000\Desktop\测试\xianshi(timer太多)\1.mdb");
con.Open();
OleDbDataAdapter adr = new OleDbDataAdapter("select * from 电主轴状态", con);
DataTable dt = new DataTable();
adr.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "电主轴运行状态";
comboBox1.ValueMember = "记录时间";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > -1)
{
DataRowView drv = (DataRowView)comboBox1.SelectedItem;
string id = drv.Row["记录时间"].ToString();
OleDbConnection con = new OleDbConnection( @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\000000\Desktop\测试\xianshi(timer太多)\1.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from 环境状态 where 记录时间=" + id + "", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
comboBox2.DataSource = dt;
comboBox2.DisplayMember = "环境状态判定";
comboBox2.ValueMember = "记录时间";
}
access 2007以上使用ace驱动而不是oledb
http://blog.163.com/qyzdmb@126/blog/static/135942386201111223039641/