private void Form1_Load(object sender, EventArgs e)
{
SqlDependency.Start(connectionString);///启动监听数据表
BindDataGridView();
}
private void BindDataGridView()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [OrderID],[ProductID],[UnitPrice],[Quantity],[Discount] FROM dbo.[Order Details]";
SqlDependency den = new SqlDependency(cmd, null, 10);//创建一个监听对象实例(cmd : 一定要写,null,是默认,10是设置的10秒)
den.OnChange += new OnChangeEventHandler(den_OnChange);///注册监听事件
////上面两句一定要放到command对象后面,不要下面这个语句里
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adp.Fill(dt);
this.dataGridView1.DataSource = dt;
}
}
}
}
void den_OnChange(object sender, SqlNotificationEventArgs e)
{
////这个方法要异步执行。
this.dataGridView1.Invoke(new MethodInvoker(delegate { BindDataGridView(); }));
}
}