please see the following example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.InitOthers();
}
private void InitOthers()
{
this.timer1.Tick += timer1_Tick;
this.timer1.Interval = 1000;
this.progressBar1.Maximum = 10;
this.button1.Click += button1_Click;
}
void button1_Click(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
this.timer1.Enabled = false;
this.timer1.Enabled = true;
this.progressBar1.Value = 0;
}
void timer1_Tick(object sender, EventArgs e)
{
if (this.progressBar1.Value < 10)
this.progressBar1.Value++;
else
this.timer1.Enabled = false;
this.listBox1.Items.Insert(0,
string.Format("tick: {0}", DateTime.Now.ToString("HH:mm:ss.fff")));
}
}
There are some points with your code:
1- (in button1_Click) You add tick handler every time when you press button1 which means tick handler will run once for the first button1 click, twice for the second click, etc. I am not sure that is what you want.
2- (in timer1_Click) You handle the case of 'not equal to 10'. What about if 'equal'? It is good practice to think about 'else' part when you handle any 'if'. Of course, you don't have to and sometimes you don't need to, but I advice you think 'if' with its 'else' part.
3- (int button1_Click) 'timer1.Enable=true' doesn't reset timer1. If it is already enabled, it continues to tick according to start time. If you want to reset it, you have to 'stop' then 'start' again.
4- (in timer1_Tick) Your custom format string for datetime has an error. no format specifier exists like 'nnn'.
the most important point is actually mentioned in comments. use your debugger to see what happens.