加几个公共属性:
加一个响应时件:
string connString = @"xyz";
System.Data.SqlClient.SqlConnection conn = null;
System.Data.SqlClient.SqlCommand command = null;
加一个开始的按钮:
conn = new System.Data.SqlClient.SqlConnection(connString);
command = conn.CreateCommand();
command.CommandText = "select code,name,spec from dbo.medicine where code='07002'";
SqlDependency.Start(connString);//启动
GetData();
加一个方法:
private void GetData()
{
command.Notification = null;//清除
SqlDependency dependency = new SqlDependency(command);//设置通知 对像每一次都要NEW
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);//事件每次都要加
using (SqlDataAdapter adapter = new SqlDataAdapter(command)) //查询数据
{
System.Data.DataSet ds = new DataSet();
adapter.Fill(ds, 0, 3, "test");
dataGridView1.DataSource = ds.Tables["test"];
}
}
加一个响应时件:
if (this.InvokeRequired)
{
this.Invoke(new OnChangeEventHandler(sqlDependency_OnChange), new object[] { sender, e });
}
else
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= sqlDependency_OnChange;
GetData();
}
也可以不用事件 当然,这个对像要设为全局:
if (dependency != null && dependency.HasChanges)
{
GetData();
}