簡體   English   中英

如何在C#Windows應用程序中通過計時器控件刷新Gridview?

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

我有一個組合框,並且在組合框中有多個選項,例如5sec,10sec,20 sec等,當我選擇任何一個選項時,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上放置一個Timer
  2. ComboBox添加到ComboBox並將其DropDownStyle屬性設置為DropDownList
  3. Form處理Load事件
  4. 處理ComboBox SelectedIndexChanged事件
  5. Timer 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM