public stugonggao() { InitializeComponent(); WindowStartupLocation = WindowStartupLocation.CenterScreen; //建立定时器,时间间隔为1s,并启动定时器 timer.Tick += new EventHandler(timer_Tick); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); //UserNameStu为登录用户名 //定义Information类型的结构体Stu gonggao gg = new gonggao(); #region 连接数据库 SqlConnection myConnection; string connStr = "Server ='" + IPAddress.ip + "'; database =测试数据库; uid =sa; pwd=1738010002"; //string connStr = @"Server = LAPTOP-25MJ4H0M\SQLEXPRESS; database =教学系统; Trusted_Connection=SSPI"; myConnection = new SqlConnection(connStr); try { myConnection.Open(); } catch (Exception) { MessageBox.Show("连接失败"); } #endregion //根据UserNameStu(登录用户名)选择出对应的个人信息 SqlCommand cmd = new SqlCommand("select 内容,时间 from ggb ", myConnection); SqlDataReader sdr = cmd.ExecuteReader(); //读取信息并对Stu结构体赋值 while (sdr.Read()) { try { gg.Info = sdr[0].ToString(); //将信息内容赋值 gg.Time = DateTime.Parse(sdr[1].ToString().Trim()); infoList1.Add(gg); //将Stu的内容返回给infoList1 } catch { } } infoList1.Sort(delegate(gonggao x, gonggao y) { return(y.Time.CompareTo(x.Time)); }); DGg.AutoGenerateColumns = false; DGg.ItemsSource = infoList1; //对DataGrid的文本框赋值 }
//手动刷新 private void Button_Click(object sender, RoutedEventArgs e) { #region 连接数据库 gonggao Stu = new gonggao(); SqlConnection myConnection; string connStr = "Server ='" + IPAddress.ip + "'; database =测试数据库; uid =sa; pwd=1738010002"; //string connStr = @"Server = LAPTOP-25MJ4H0M\SQLEXPRESS; database =教学系统; Trusted_Connection=SSPI"; myConnection = new SqlConnection(connStr); try { myConnection.Open(); } catch (Exception) { MessageBox.Show("连接失败"); } #endregion //根据UserNameStu(登录用户名)选择出对应的个人信息 SqlCommand cmd = new SqlCommand("select 内容,时间 from ggb ", myConnection); SqlDataReader sdr = cmd.ExecuteReader(); //清空infoList1的内容 infoList1.Clear(); //读取信息并对Stu结构体赋值 while (sdr.Read()) { Stu.Info = sdr[0].ToString(); //将信息内容赋值 Stu.Time = DateTime.Parse(sdr[1].ToString()); infoList1.Add(Stu); //将Stu的内容返回给infoList1 } infoList1.Sort(delegate(gonggao x, gonggao y) { return(y.Time.CompareTo(x.Time)); }); DGg.AutoGenerateColumns = false; DGg.ItemsSource = null; //将DataGrid清空 DGg.ItemsSource = infoList1; //对DataGrid的文本框赋值 }