public QuestionWindow() { InitializeComponent(); WindowStartupLocation = WindowStartupLocation.CenterScreen; //建立定时器,时间间隔为1s,并启动定时器 timer.Tick += new EventHandler(timer_Tick); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); //UserName为提问学生的账户名 string n = MainWindow.UserCode; string UserNameStu = n.ToString(); StuQuestion Stu = new StuQuestion(); //数据库连接 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("连接失败"); } //从表中查询问题相关信息并显示 SqlCommand cmd = new SqlCommand("select 问题,答案,状态,时间 from wtb where 学号 = '" + UserNameStu + "'", myConnection); SqlDataReader sdr = cmd.ExecuteReader(); while (sdr.Read()) { Stu.Status = sdr[2].ToString(); Stu.Question = sdr[0].ToString(); Stu.Answer = sdr[1].ToString(); Stu.Time = DateTime.Parse(sdr[3].ToString().Trim()); infoList.Add(Stu); } //比较时间大小,将问题排序 infoList.Sort(delegate(StuQuestion x, StuQuestion y) { return(y.Time.CompareTo(x.Time)); }); DG1.AutoGenerateColumns = false; DG1.ItemsSource = infoList; }
/// <summary> /// 手动刷新 /// </summary> private void Button_Click_1(object sender, RoutedEventArgs e) { DG1.ItemsSource = null; string n = MainWindow.UserCode; string UserNameStu = n.ToString(); StuQuestion Stu = new StuQuestion(); 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("连接失败"); } SqlCommand cmd = new SqlCommand("select 问题,答案,状态,时间 from wtb where 学号 = '" + UserNameStu + "'", myConnection); SqlDataReader sdr = cmd.ExecuteReader(); infoList.Clear(); while (sdr.Read()) { Stu.Status = sdr[2].ToString(); Stu.Question = sdr[0].ToString(); Stu.Answer = sdr[1].ToString(); Stu.Time = DateTime.Parse(sdr[3].ToString().Trim()); infoList.Add(Stu); } infoList.Sort(delegate(StuQuestion x, StuQuestion y) { return(y.Time.CompareTo(x.Time)); }); DG1.AutoGenerateColumns = false; DG1.ItemsSource = null; DG1.ItemsSource = infoList; }