2014-06-15 24 views
0

我有一個項目,其中我有一個listBox1一個timer1一個button1和一個progressBar1。如何同步進度條與列表框項目刪除c#

當我點擊button1時,timer1啓動。

private void button1_Click(object sender, EventArgs e) 
    { 
     timer1.Enabled = true; 
     timer1.Interval = 500; 
     progressBar1.Maximum = listBox1.Items.Count; 
     progressBar1.Value = 0; 
    } 

當定時器1蜱從listBox1中和progressBar1刪除一個項目必須顯示刪除進度。

private void timer1_Tick(object sender, EventArgs e) 
    { 
     timer1.Enabled = false; 
     if (listBox1.Items.Count > 0) 
     { 

      listBox1.Items.RemoveAt(0); 
      progressBar1.Increment(1); 
      groupBox1.Text = listBox1.Items.Count.ToString(); 
     } 
     if (listBox1.Items.Count > 0) 
     { 
      timer1.Enabled = true; 
      progressBar1.Maximum = listBox1.Items.Count; 
      progressBar1.Value = 0; 
     } 
    } 

但我認爲上面的代碼中得到了與progressBar1一些bug,因爲它不顯示進度,同時取走物品,它是全時爲ListBox項目= 0

回答

1

有比這更好的辦法,所以在點擊事件設置步驟屬性如下:

 this.progressBar1.Minimum = 0; 
     this.progressBar1.Value = 0; 
     this.progressBar1.Maximum = this.listBox1.Items.Count; 
     progressBar1.Step = 1; 

現在,你可以做到以下幾點:

void timer1_Tick(object sender, EventArgs e) 
    { 
     if (listBox1.Items.Count > 0) 
     { 

      listBox1.Items.RemoveAt(0); 
      progressBar1.PerformStep(); 
      groupBox1.Text = listBox1.Items.Count.ToString(); 
     } 
     else 
     { 
      this.timer1.Enabled = false; 
     } 
    } 

完整代碼:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     PopulateList(); 
    } 

    private void PopulateList() 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      listBox1.Items.Add(i); 
     } 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (listBox1.Items.Count > 0) 
     { 
      listBox1.Items.RemoveAt(0); 
      progressBar1.PerformStep(); 
      groupBox1.Text = listBox1.Items.Count.ToString(); 
     } 
     else 
     { 
      timer1.Enabled = false; 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     timer1.Tick += timer1_Tick; 
     timer1.Enabled = true; 
     timer1.Interval = 500; 
     progressBar1.Enabled = true; 
     progressBar1.Visible = true; 
     progressBar1.Minimum = 0; 
     progressBar1.Value = 0; 
     progressBar1.Maximum = listBox1.Items.Count; 
     progressBar1.Step = 1; 
    } 
} 
+0

進度條在您的代碼中不起作用。 –

+0

你是否啓用了按鈕點擊定時器?在我們設置進度條上的最大值之前,還有列表框項目嗎? – Avneesh

+0

是的,我已啓用計時器並設置click.yes列表框項目生成之前單擊事件。 –

1

你之後進度值設置爲0增加它...

試試這個:

private void timer1_Tick(object sender, EventArgs e) 
{ 
    timer1.Enabled = false; 
    if (listBox1.Items.Count > 0) 
    { 
     listBox1.Items.RemoveAt(0); 
     progressBar1.Increment(1); 
     groupBox1.Text = listBox1.Items.Count.ToString(); 
     timer1.Enabled = true; 
    } 
} 
+0

您的代碼將拋出的時候會有在listBox1中0項異常。 –

+0

爲什麼呢?我們只是在刪除項目時:if(listBox1.Items.Count> 0) – jmelhus

+0

謝謝@ jmelhus我知道了// –