我正在尝试为添加到dataGridView的每一行添加一个计时器,如果删除了一行则将其删除。
由于错误,我无法让计时器运行:
'System.Timers.Timer'不包含'Tick'的定义,并且没有扩展方法'Tick'接受类型为'System.Timers.Timer'的第一个参数'(您是否缺少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
}
谢谢你们的任何帮助。
答案 0 :(得分:2)
答案 1 :(得分: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)
。