DataGridView实现倒计时功能(源码)

 需求:最近做一个即时通项目,需要结合OA项目;其中有一个待办事项需要倒计时,准备在DataGridView里展示,如图:

DataGridView实现倒计时功能(源码)

第一步:绑定数据

  for (int intLoop = 1; intLoop <= 5; intLoop++)
            {
                this.dgvSteps.Rows.Add(
                    Test.Properties.Resources.PROCESS_READY,
                    intLoop.ToString(),
                    "" + intLoop.ToString() + "个任务&为开始",
                    "{0}天{1}小时{2}分钟{3}秒",
                    "处理"
                    );
            }

第二步:定义System.Threading.Timer(一定要在定义局部变量,不然会被回收的)

DateTime dtStart;
        private System.Threading.Timer timerClose;
        private void btnStart_Click(object sender, EventArgs e)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            timerClose = new System.Threading.Timer(new TimerCallback(timerCall), autoEvent, 1000, 1000);
            dtStart = DateTime.Now.AddHours(5);
        }

        private void timerCall(object obj)
        {

            TimeSpan ts = dtStart - DateTime.Now;
            if (ts < TimeSpan.Zero)
            {
                for (int i = 0; i < this.dgvSteps.Rows.Count; i++)
                {
                    this.dgvSteps.Rows[i].Cells[3].Value = "超时";
                }
            }
            else
            {
                for (int i = 0; i < this.dgvSteps.Rows.Count; i++)
                {
                    this.dgvSteps.Rows[i].Cells[3].Value = string.Format("{0}天{1}小时{2}分钟{3}秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds);
                }
            }
          
        }

 

 源码地址:下载

 

你可能感兴趣的:(datagridview)