使用 Backgroundworker 将大量数据加载到 ListViewItem
当我要打开一个表单时,我无法加载大量数据。所以我所做的是在我的表单中实现了一个 BackgroundWorker 组件,这就是我的代码的样子。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int x = 1; x <= 100; x++)
{
loadDataByAll(); //Loads All Data to ListView
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.ReportProgress(x);
}
}
对于流程更改事件代码
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
对于 loadDataByAll() 函数
private void loadDataByAll()
{
try
{
lviewGuard.Items.Clear();
con.ConnectionString = dbcon.getConnectionString();
con.Open();
String query = "SELECT guardid AS a, g_firstname AS b, g_midname AS c, g_lastname AS d, g_age AS e, g_gender AS f, g_address AS g, g_contactno AS h, g_licno AS i, g_lic_until AS j, g_assigned_client AS k, g_schedule_from AS l, g_schedule_to AS m, app_no AS n";
query += " FROM guards";
query += " WHERE resigned = '0' ORDER BY app_no DESC";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.ExecuteScalar();
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lviewGuard.BeginUpdate();
ListViewItem lv = new ListViewItem(rdr["a"].ToString());
lv.SubItems.Add(rdr["b"].ToString());
lv.SubItems.Add(rdr["c"].ToString());
lv.SubItems.Add(rdr["d"].ToString());
lv.SubItems.Add(rdr["e"].ToString());
lv.SubItems.Add(rdr["f"].ToString());
lv.SubItems.Add(rdr["g"].ToString());
lv.SubItems.Add(rdr["h"].ToString());
lv.SubItems.Add(rdr["i"].ToString());
lv.SubItems.Add(rdr["j"].ToString());
lv.SubItems.Add(rdr["k"].ToString());
lv.SubItems.Add(rdr["l"].ToString());
lv.SubItems.Add(rdr["m"].ToString());
lv.SubItems.Add(rdr["n"].ToString());
lviewGuard.Items.Add(lv);
lviewGuard.EndUpdate();
}
con.Close();
}
catch (Exception)
{
MessageBox.Show("MDB Database is not Present", "Microsoft Access Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
最后是我的按钮实现
private void btnGo7_Click(object sender, EventArgs e)
{
for (int x = 1; x <= 100; x++)
{
btnGo7.Text = "Running";
btnGo7.Enabled = false;
}
btnGo7.Text = "Go";
btnGo7.Enabled = true;
progressBar1.Value = 0;
tabControl1.Visible = false;
}
很抱歉浪费您的时间阅读此代码。对于这个多线程和后台工作,我真的是一个完全的菜鸟。