|
private void frmToolBarMenu_Load(object sender, EventArgs e)
{
listView1.TemplateControl = new UserControl.messagelayout();
SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
UpdateGrid();
}
int i=1;
public void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
using (SqlCommand command = new SqlCommand("SELECT ID,status,message,date,uid,del FROM [dbo].[HE_Notice]", connection))
{
command.CommandType = CommandType.Text;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
this.Invoke((EventHandler)(delegate
{
label1.Text = (i++).ToString();
}), new object[] { null, null });
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
{
UpdateGrid();
}
}
使用dependency监测sql数据表变化时触发UpdateGrid(),测试代码如上,为何在sql表变化时,label1.text赋值显示无变化?
|
|