C#中使用backgroundworker進行進度條進度顯示

想用C#顯示進度條,比如向數據庫中寫入1000條記錄,動態顯示寫入進度。效果如下:

主要代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Threading;

namespace ServiceSet
{
    public partial class Form1 : Form
    {
        private int sum = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: 這行代碼將數據加載到表“equipDBDataSet.Equipment”中。您可以根據需要移動或刪除它。
            this.equipmentTableAdapter.Fill(this.equipDBDataSet.Equipment);

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            sum = Convert.ToInt32(tbNum.Text);
            backgroundWorker1.RunWorkerAsync();
            progressBar1.Maximum = sum;
            progressBar1.Value = 0;
            progressBar1.Step = 1;
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            this.equipmentTableAdapter.DeleteQueryAll();

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            
            for (int i = 0; i < sum; i++)
            {
                this.equipmentTableAdapter.Insert("單位"+i.ToString(),"名稱"+i.ToString(),"備註"+i.ToString());
                worker.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            labelSum.Text = string.Format("已添加{0}條記錄", (e.ProgressPercentage+1).ToString());
            progressBar1.Value++;

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("添加完畢!");
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章