我想在我的c#應用程序中顯示一個進度條。有一個函數,我正在調用按鈕單擊在我的應用程序中,這是耗時的,不可能確定它需要多少時間以完成整個過程,因爲我正在從Excel表格讀取數據並存儲到數據庫和所有東西。當我點擊按鈕進度條應顯示正確的狀態,當整個過程完成時,我想顯示一條消息的「成功完成」。在c中使用進度條#
AlertForm alert;
private void btnImport_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
// create a new instance of the alert form
alert = new AlertForm();
// event handler for the Cancel button in AlertForm
alert.Canceled += new EventHandler<EventArgs>(buttonCancel_Click);
alert.Show();
backgroundWorker1.RunWorkerAsync();
StartConversion(txtPath.Text.Trim(), Path.GetFileName(txtPath.Text.Trim()));
}
}
#region Progress bar EVENTS
private void buttonStart_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
// create a new instance of the alert form
alert = new AlertForm();
// event handler for the Cancel button in AlertForm
alert.Canceled += new EventHandler<EventArgs>(buttonCancel_Click);
alert.Show();
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
// This event handler cancels the backgroundworker, fired from Cancel button in AlertForm.
private void buttonCancel_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
// Close the AlertForm
alert.Close();
}
}
// This event handler is where the time-consuming work is done.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
worker.ReportProgress(i * 10);
System.Threading.Thread.Sleep(500);
}
}
}
// This event handler updates the progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Show the progress in main form (GUI)
labelResult.Text = (e.ProgressPercentage.ToString() + "%");
// Pass the progress to AlertForm label and progressbar
alert.Message = "In progress, please wait... " + e.ProgressPercentage.ToString() + "%";
alert.ProgressValue = e.ProgressPercentage;
}
// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
labelResult.Text = "Canceled!";
}
else if (e.Error != null)
{
labelResult.Text = "Error: " + e.Error.Message;
}
else
{
labelResult.Text = "Done!";
}
// Close the AlertForm
alert.Close();
}
#endregion
檢測AlertForm Ia的我的應用程序的另一種形式,其用於顯示進度條 StartConversion()方法是調用另一個方法,其是本其actualy執行耗時的任務的一類內的方法。
我該如何實現這個任務? 請幫我....
你幾乎說一步一步,你需要做什麼。所以......就這樣做? – Luaan
你在'win-form'中工作嗎? –
你會發現這個網站不是一個代碼寫作服務。您需要攜帶代碼來向我們展示您正在做的事情,然後我們才能幫您指出正確的方向。 – Enigmativity