如何同步进度条与ListBox项目删除c#

时间:2014-06-15 08:12:10

标签: c#

我有一个项目,其中我有一个listBox1一个timer1一个button1和一个progressBar1。

当我点击button1时,timer1启动。

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

当timer1勾选时,它会从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中遇到了一些错误,因为它在删除项目时没有显示进度,而当listBox1项目= 0时它已满。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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;
    }
}