【问题标题】:Add count down to data grid view every time button is pressed. Then delete row after countdown reaches 0每次按下按钮时,都会向数据网格视图添加倒计时。然后在倒计时到0后删除行
【发布时间】:2017-01-05 17:03:59
【问题描述】:

我正在尝试将倒计时添加到从 2 分钟到 0 的数据网格视图。当按下按钮时,它应该添加一个带有标记和 2 分钟倒计时的新行。当 2 分钟倒计时达到 0 时,应删除该行。我已经设置了令牌,目前我正在使用 2 分钟内的时间而不是倒计时。我想要实现的主要目标是在令牌过期 2 分钟后删除令牌。

这是我当前的代码:

        //Add Token To Grid
        int row = 0;
        TokenGrid.Rows.Add();
        row = TokenGrid.Rows.Count - 2;
        TokenGrid["CaptchaToken", row].Value = CaptchaWeb.Document.GetElementById("gcaptcha").GetAttribute("value");
        //Time Left
        TokenGrid["ExpiryTime", row].Value = DateTime.Now.AddMinutes(2).ToLongTimeString();

【问题讨论】:

  • 你使用任何类型的计时器吗?
  • 我有一个计时器,但它只用于显示当前时间。

标签: c#


【解决方案1】:

在定时器的timeelapsed()事件中,将每一行的值ExpiryTime与当前时间进行比较。如果ExpiryTime < current time,则删除该行。

【讨论】:

    【解决方案2】:

    实现一个定时器(见How do I create a timer in WPF?):

    const int MAX_DURATION = 120;
    System.Windows.Threading.DispatcherTimer dispatcherTimer;
    
    // In the OnClick
    DateTime timerStart = DateTime.Now;
    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    EventHandler handler = new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Tick += handler;
    dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
    dispatcherTimer.Start();
    
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
         // Display seconds 
         var currentValue = DateTime.Now - timerStart; 
         TokenGrid["ExpiryTime", row].Value = currentValue.Seconds.ToString();
    
         // When the MAX_DURATION (2 minutes) is reached, stop the timer
         if (currentValue >= MAX_DURATION) {
             dispatcherTimer.Tick -= handler;
             dispatcherTimer.Stop();
             TokenGrid.Rows.RemoveAt(row);
         }
    }
    

    【讨论】:

    • 我使用的是 Winforms 而不是 WPF。我找不到“System.Windows.Threading”名称空间,也不知道将代码的第一部分放在哪里。
    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多