更新DataGridView 还是更新绑定的DataSource?
Update DataGridView or update the binded DataSource?
我正在做一个 C#
项目,其中 DataGridView
在运行时显示在 WinForm
中,需要每 2~3 秒更新一次。每个DataGridView
的DataSrouce
绑定一个DataSet
,可以根据用户的操作改变。
由于我完全是C#
的新手,我不知道应该如何在GUI中实现表单的实时刷新。当然我需要多线程,以便显示的数据更新可以在后台完成并且 GUI 不会挂起。
PS:在 Qt
中,每个 view
都绑定到一个 model
,我可以在与主线程不同的线程中更新每个 model
GUI 线程,使 GUI 不会卡住。这就是我现在正在做的。下面是示例代码。
// MainForm.cs
public Bind()
{
dataGridView.DataSource = TableCollection.DataTable1;
}
public StartTimer()
{
System.Windows.Forms.Timer tdfTimer = new System.Windows.Forms.Timer();
guiTimer.Tick += new EventHandler(Refresh);
guiTimer.Interval = 500;
guiTimer.Start();
}
public void Refresh(object sender, EventArgs e)
{
if (backgroundwork == null)
{
backgroundwork = new BackgroundWorker();
backgroundwork.DoWork += delegate(object s, DoWorkEventArgs args) { TableCollection.UpdateData(); };
}
if (!backgroundwork.IsBusy)
backgroundwork.RunWorkerAsync();
}
// TableCollection.cs
class TableCollection
{
static DataTable dataTable1;
public DataTable1
{
get { return dataTable1; }
}
static public void UpdateData()
{
// here i update each row in dataTable1
}
}
你想经常更新 datagridview 所以你必须为 that.the 创建 BindingSource 代码应该看起来像
BindingSource DGSource = new BindingSource(TableCollection.DataTable1, null);
dataGridView2.DataSource = DGSource;
我正在做一个 C#
项目,其中 DataGridView
在运行时显示在 WinForm
中,需要每 2~3 秒更新一次。每个DataGridView
的DataSrouce
绑定一个DataSet
,可以根据用户的操作改变。
由于我完全是C#
的新手,我不知道应该如何在GUI中实现表单的实时刷新。当然我需要多线程,以便显示的数据更新可以在后台完成并且 GUI 不会挂起。
PS:在 Qt
中,每个 view
都绑定到一个 model
,我可以在与主线程不同的线程中更新每个 model
GUI 线程,使 GUI 不会卡住。这就是我现在正在做的。下面是示例代码。
// MainForm.cs
public Bind()
{
dataGridView.DataSource = TableCollection.DataTable1;
}
public StartTimer()
{
System.Windows.Forms.Timer tdfTimer = new System.Windows.Forms.Timer();
guiTimer.Tick += new EventHandler(Refresh);
guiTimer.Interval = 500;
guiTimer.Start();
}
public void Refresh(object sender, EventArgs e)
{
if (backgroundwork == null)
{
backgroundwork = new BackgroundWorker();
backgroundwork.DoWork += delegate(object s, DoWorkEventArgs args) { TableCollection.UpdateData(); };
}
if (!backgroundwork.IsBusy)
backgroundwork.RunWorkerAsync();
}
// TableCollection.cs
class TableCollection
{
static DataTable dataTable1;
public DataTable1
{
get { return dataTable1; }
}
static public void UpdateData()
{
// here i update each row in dataTable1
}
}
你想经常更新 datagridview 所以你必须为 that.the 创建 BindingSource 代码应该看起来像
BindingSource DGSource = new BindingSource(TableCollection.DataTable1, null); dataGridView2.DataSource = DGSource;