如何在 C# Windows 应用程序中通过计时器控件刷新 Gridview?

How to Refresh a Gridview by a Timer Control in C# Windows Application?

我有一个组合框,在组合框中我有多个选项,如 5 秒、10 秒、20 秒等,当我 select 任何一个选项时,gridview 在该特定时间后刷新。 以下是在 datagridview 中加载文件的代码。

public string Path { get; set; }
private void UploadButton_Click(object sender, EventArgs e)
{
    var o = new OpenFileDialog();
    o.Multiselect = true;
    if(o.ShowDialog()== System.Windows.Forms.DialogResult.OK)
    {
        o.FileNames.ToList().ForEach(file=>{
            System.IO.File.Copy(file, System.IO.Path.Combine(this.Path, System.IO.Path.GetFileName(file)));
        });
    }

    this.LoadFiles();
}

private void Form_Load(object sender, EventArgs e)
{
    this.LoadFiles();
}

private void LoadFiles()
{
    this.Path = @"d:\Test";
    var files = System.IO.Directory.GetFiles(this.Path);
    this.dataGridView1.DataSource = files.Select(file => new { Name = System.IO.Path.GetFileName(file), Path = file }).ToList();
}

按照以下步骤操作:

  1. 在你的 Form
  2. 上放一个 Timer
  3. 将 5、10、20 添加到您的 ComboBox 并将其 DropDownStyle 属性 设置为 DropDownList
  4. 处理 Load 事件 Form
  5. 处理 ComboBox
  6. SelectedIndexChanged 事件
  7. 处理 Timer
  8. Tick 事件

编写代码:

private void Form1_Load(object sender, EventArgs e)
{
    //Setting 0 as selected index, makes SelectedIndexChanged fire
    //And there we load data and enable time to do this, every 5 seconds
    this.comboBox1.SelectedIndex = 0; //To load each 5 seconds
}

private void LoadFiles()
{
    //Load Data Here
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.timer1.Stop();
    this.LoadFiles(); //optional to load data when selected option changed
    this.timer1.Interval = Convert.ToInt32(this.comboBox1.SelectedItem) * 1000;
    this.timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.LoadFiles();
}