用户
 找回密码
 立即注册

6

主题

8

帖子

240

积分

中级会员

Rank: 3Rank: 3

积分
240
发表于 2021-2-1 17:56:03
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赋值显示无变化?

分享至 : QQ空间
0 人收藏
使用道具 举报 回复
发表于 2021-2-2 16:08:01
可以再最后使用this.Client.RenderFlush()刷新界面
使用道具 举报 回复 支持 反对
发新帖
您需要登录后才可以回帖 登录 | 立即注册