Razim Khan
Razim Khan

Reputation: 347

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

I have a combobox and in the combobox I have multiple options like 5sec, 10sec 20 sec, etc, when I select any one option the gridview refreshes after that specific time. Following is code which load files in 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();
}

enter image description here

Upvotes: 1

Views: 2966

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

Follow these steps:

  1. Put a Timer on your Form
  2. Add 5, 10, 20 to your ComboBox and set its DropDownStyle property to DropDownList
  3. Handle Load event of Form
  4. Handle SelectedIndexChanged event of ComboBox
  5. Handle Tick event of Timer

Write Codes:

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();
}

Upvotes: 1

Related Questions