[英]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();
}
跟着這些步驟:
Form
上放置一個Timer
ComboBox
添加到ComboBox
並將其DropDownStyle
屬性設置為DropDownList
Form
處理Load
事件 ComboBox
SelectedIndexChanged
事件 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.