0

我正在尝试为添加到 dataGridView 的每一行添加一个计时器,并在删除一行时将其删除。

由于错误,我根本无法让计时器运行:

“System.Timers.Timer”不包含“Tick”的定义,并且找不到接受“System.Timers.Timer”类型的第一个参数的扩展方法“Tick”(您是否缺少 using 指令或程序集引用?)

当前上下文中不存在名称“myTimer_Tick”

这是我所拥有的一个例子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Data.OleDb;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Timers;

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    System.Timers.Timer myTimer = new System.Timers.Timer();
    myTimer.Interval = 30000;
    myTimer.Tick += new EventHandler(myTimer_Tick);
    myTimer.Enabled = true;
    myTimer.Start();
}

public void MyTimer_Tick(object sender, EventArgs e)
{
    MessageBox.Show("30 seconds scince you added a row");
}

private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
    //remove a timer here that corresponds to this row, 
    //if row removed before timer elapsed
}

感谢您为我提供的任何帮助。

4

2 回答 2

2

你应该使用

System.Windows.Forms.Timer

代替

using System.Timers;

这里这里

于 2013-03-18T17:28:17.933 回答
1

首先,System.Timer没有.Tick事件。改用Timer.Elapsed

myTimer.Elapsed += new EventHandler(MyTimer_Tick);

[编辑:用字典替换列表]

您还需要多个计时器以及将计时器保持在范围内的方法。使用Dictiory<DataGridViewRow, Timer>在类级别声明的对象:

private Dictionary<DataGridViewRow, System.Timers.Timer> timers = new Dictionary<DataGridViewRow, System.Timers.Timer>();

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    var myTimer = new System.Timers.Timer();
    myTimer.Interval = 30000;
    myTimer.Elapsed += new ElapsedEventHandler(MyTimer_Tick);
    myTimer.Enabled = true;

    // Potential bug source: If you programmatically add multiple rows at once,
    // a timer is only added to the first row
    timers.Add(dataGridView1.Rows[e.RowIndex], myTimer);
}

现在在 RowsRemoved 事件处理程序中,您获取行索引并将其从timers字典中删除;例如,timers.RemoveAt(rowIndex)

于 2013-03-18T17:36:30.570 回答