在新的一年开始接受正式培训之前,我正在慢慢地掌握C#,并且正在玩游戏。 我创建了一个应用程序,该应用程序从SQL数据库中提取数据并显示在dataGridView中。该表的大小可能非常大,可能需要一些时间来加载。这次我已经更改了光标,以便用户可以看到正在发生的事情。但是我想添加一个过程栏。我已经厌倦了一些没有运气的教程。我已经在名为doTask()的方法中创建了任务。我尝试使用Backgroundworker,但是由于某些原因,我的过程栏从不更新。所有的教程似乎都只是使用计时器而不是真正的任务,这无济于事。
从我看过的视频中,当您调用RunWorkerAsync()时,该视频又会运行该方法?
任何帮助都会很棒
public Form1()
{
InitializeComponent();
MessageBox.Show("Internal use only. Do NOT sent installers or customers", "INTERNAL USE ONLY", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
private void getEventsbtn_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = 10;
backgroundWorker1.RunWorkerAsync();
// doTask();
}
public void doTask()
{
DataTable dt = new DataTable("Events");
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
if (cn.State == ConnectionState.Closed)
cn.Open();
this.Cursor = Cursors.WaitCursor;
SqlCommand cmd2 = new SqlCommand(@"
Select e.EventTime as 'Date/time', u.Username as 'User', e.CardNo as 'Token number', dev.PeripheralName as 'Where' , et.EventTypeDescription as 'Event', est.EventSubTypeDescription as 'Details'
FROM Archive.dbo.Events e
left join sdk.EventSubTypes est
on e.EventSubType = est.EventSubTypeID
join sdk.EventTypes et
on e.EventType = et.EventTypeID
join sdk.UsersEx as u
on e.UserID = u.UserID
join sdk.PeripheralNames as dev
on e.Address = dev.SerialNumber
order by EventTime asc
", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
archievegridview.DataSource = dt;
label2.Text = archievegridview.Rows.Count.ToString();
if (archievegridview.Rows.Count < 2)
{
MessageBox.Show("No Net2Archive data available", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
cn.Close();
this.Cursor = Cursors.Default;
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
doTask();
backgroundWorker1.ReportProgress(0);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value += 1;
}
}
}