业务:计时刷新DataGridView
Task.Factory.StartNew(() =>
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = config.dowDataRate; // 执行间隔时间
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(MachingDownInfo.DownMachingFile);
});
开了一个线程,来获取DataGridView的数据。我的思路本来是直接在这个计时方法中绑定当前窗体的DataGridView控件的值。
此问题的原因,自己总结了一下:DataGridView控件不能在类中绑定数据。
最后反复测试,找到了解决方案。
Task.Factory.StartNew(() =>
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = config.dowDataRate; // 执行间隔时间
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(MachingDownInfo.DownMachingFile);
// 动态刷新列表数据
System.Timers.Timer timer1 = new System.Timers.Timer();
timer1.Enabled = true;
timer1.Interval = (config.dowDataRate / 2); // 执行间隔时间
timer1.Start();
timer1.Elapsed += new System.Timers.ElapsedEventHandler(BindGridListTimer);
});
声明了两个计时器,第二个是刷新列表的。绑定列表的时间间隔设置的为取列表数据时间间隔的一半。
private void BindGridListTimer(object source, ElapsedEventArgs e)
{
try
{
SetGridData();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
// 声明委托
private delegate void SetGridDelegate();
/// <summary>
/// 委托将参数与方法传递给控件所在的线程,并由控件所在的线程执行
/// </summary>
public void SetGridData()
{
if (this.InvokeRequired)
this.Invoke(new SetGridDelegate(SetGridData));
else
BindGrid();
}
static DataTable dtCsvGrid = new DataTable();
/// <summary>
/// CSV列表,在执行**MachingDownInfo.DownMachingFile**方法时会给此变量赋值。![在这里插入图片描述]
/// </summary>
public DataTable _dtCsvGrid
{
get { return dtCsvGrid; }
set { dtCsvGrid = value; }
}
/// <summary>
/// 绑定设备保养信息grid列表数据
/// </summary>
/// <returns></returns>
public void BindGrid()
{
dataGridView1.DataSource = dtCsvGrid;
}
以上经过测试,可行! 虽然有点笨拙。但是我看到列表刷新的那一刻,超级激动啊!!!!