C# Winform ProgressBar+Labe 联动显示进度
private void btnCount_Click(object sender, EventArgs e) { label1.Visible=true; progressBar.Visible = true; progressBar.Minimum = 0; progressBar.Maximum = ds.Tables["表"].Rows.Count; progressBar.BackColor = Color.Green; for (int i = 0; i < ds.Tables["表"].Rows.Count; i++) { progressBar.Value++; Application.DoEvents(); this.label1.Text = Convert.ToString(progressBar.Value); } } 或者 private void btnCount_Click(object sender, EventArgs e) { label1.Visible=true; progressBar.Visible = true; progressBar.Minimum = 0; progressBar.Maximum = ds.Tables["表"].Rows.Count; progressBar.BackColor = Color.Green; for (int i = 0; i < ds.Tables["表"].Rows.Count; i++) { progressBar.Value++; Application.DoEvents(); this.label1.Text = Convert.ToString(progressBar.Value);this.label1.Refresh(); } }
或简单点:
private void Form1_Load(object sender, EventArgs e) { int nMax = 100; progressBar1.Maximum = nMax; Task.Factory.StartNew(() => { for (int i = 1; i <= 100; i++) { SetVal(i, nMax); Thread.Sleep(50); } }); } private void SetVal(int nVal, int nMax) { if (this.InvokeRequired) this.BeginInvoke(new Action(() => { SetVal(nVal, nMax); })); else { textBox1.Text = nVal.ToString(); progressBar1.Value = nVal; label1.Text = $"{nVal}/{nMax}"; } }