主要控件有 datagridview checkbox picturebox trackBar1 label
datagridview :实时显示数据
checkbox :指示是否停止更新
picturebox :显示更新状态
trackBar1 :设置更新时间频率
label :显示一些相关信息
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.Threading; 9 10 namespace WinMilkProject.Project 11 { 12 13 public partial class Form1 : Form 14 { 15 Thread myThread; 16 OperateCB operatedb = new OperateCB(); 17 public int frequency = 0;//更新时间频率 18 public static bool isUse = false;//是否停止更新 19 public static string statusInfo = string.Empty;//状态 20 private delegate void myDelegate(DataTable dt);//定义委托 21 public Form1() 22 { 23 InitializeComponent(); 24 label2.Text = "更新频率为:" + (trackBar1.Value / 1000).ToString() + "秒"; 25 } 26 27 private void Form1_Load(object sender, EventArgs e) 28 { 29 myThread = new Thread(startFillDv);//实例化线程 30 myThread.Start(); 31 32 } 33 34 private void startFillDv() 35 { 36 while (true) 37 { 38 if (isUse) 39 { 40 statusInfo = "正在实时更新数据......"; 41 DataTable dt = operatedb.MyDataTable("select * from test1");//把自己写的数据封装类OperaterCB 能够返回一个datatable 42 Grid(dt); 43 Thread.Sleep(frequency); 44 } 45 else 46 { 47 statusInfo = "停止更新!"; 48 } 49 } 50 51 } 52 53 private void Grid(DataTable dt) 54 { 55 if (this.InvokeRequired) 56 { 57 this.Invoke(new myDelegate(Grid), new object[] { dt }); 58 } 59 else 60 { 61 try 62 { 63 this.dataGridView1.DataSource = null; 64 this.dataGridView1.DataSource = dt; 65 dt = null; 66 statusInfo = "更新完成!"; 67 } 68 catch 69 { 70 71 } 72 } 73 74 } 75 76 private void Form1_FormClosed(object sender, FormClosedEventArgs e) 77 { 78 if (this.myThread.IsAlive) 79 { 80 this.myThread.Abort();//结束线程 81 } 82 } 83 84 private void timer1_Tick(object sender, EventArgs e) 85 { 86 label1.Text = statusInfo; 87 frequency = trackBar1.Value; 88 if (statusInfo.Trim() == "正在实时更新数据......") 89 { 90 pictureBox1.Visible = true; 91 } 92 else 93 { 94 pictureBox1.Visible = false; 95 } 96 97 } 98 99 private void checkBox1_CheckedChanged(object sender, EventArgs e) 100 { 101 if (checkBox1.Checked) 102 { 103 isUse = true; 104 } 105 else 106 { 107 isUse = false; 108 } 109 110 } 111 112 private void trackBar1_Scroll(object sender, EventArgs e) 113 { 114 label2.Text = "更新频率为:" + (trackBar1.Value / 1000).ToString() + "秒"; 115 } 116 117 } 118 }
效果图如下: