在Windows窗体应用程序中显示进度条 [英] Show progress bar in windows forms application
问题描述
嗨
i想在我的Windows窗体应用程序中使用进度条。
i尝试使用< b> BackgroundWorker 来自此链接 http://eclipsed4utoo.com/blog/windows-form-progressbar/ [ ^ ]。
在我的表单上点击按钮,它将数据从SQL数据库下载到XML文件,数据下载需要8到10秒。在那个时候我想显示进度条。
这里问题是从SQL下载到XML后代码显示进度条。
这里是下面的代码
hi
i want to use progress bar in my windows form application.
i tried using BackgroundWorker from this link http://eclipsed4utoo.com/blog/windows-form-progressbar/[^].
In my form on button click it downloads data from SQL database to XML file, it takes 8 to 10 sec for data downloading.in that time i would like to show progress bar.
here problem is progress bar is showing after code downloaded from SQL to XML.
here is the code below
bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
private void btnSubmitEventId_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync(); // called RunWorkerAsync in my button click
// here my code for data downloading
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
bgw.ReportProgress((i + 1) * 10);
Thread.Sleep(1000);
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Finished");
}
here i understand that ReportProgress raises the bgw_ProgressChanged and assigned progress ercentage to progressBar1.Value that is fine but here ReportProgress raises bgw_ProgressChanged method after my data downloading is completed.
plz help me to find this out.
推荐答案
解决方案可能类似于:
Solution may be something like:
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.BeginInvoke(new MethodInvoker(pb => pb.Value = e.ProgressPercentage));
}
由于您尝试从与创建它的线程不同的线程更新UI元素(您的ProgressBar),您必须使用BeginInvoke ()方法。
希望这会有所帮助。
[edit]更新以构建委托作为参数for BeginInvoke()[/ edit]
Since you are trying to update an UI element (your ProgressBar) from a different thread than the one which has created it, you have to use BeginInvoke() method.
Hope this helps.
[edit] Updated to construct a delegate as parameter for BeginInvoke() [/edit]
这篇关于在Windows窗体应用程序中显示进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!