Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
I have Form1 and Form2.

I have a Timer in Form1, named timer.

Now, when the user clicks on the Pause button in Form1, Form2 pops up, and the timer pauses.

When the user clicks on button1 on Form2, Form2 will close and the timer is supposed to continue running, but right now I can't make it happen.

Here's what I've tried so far:

On Form1:

C#
private void btnPause_Click(object sender, EventArgs e)
{
    timer.Stop();
    new Form2(this).ShowDialog();

}

//and a method Form2 can call to start the timer again
public void startTimer()
{
    timer.Start();
}


And on Form2:
C#
Form f1;
Form1 form1 = new Form1();

public Form2(Form1 f)
{
    this.f1 = f;

}
private void button1_Click(object sender, EventArgs e)

{
    form1.startTimer();
    this.Close();

}


I'm referencing since there's also another button on Form2 that when clicked will close Form2 and Form1 and will show another form.
I'm not sure if I should actually instantiate Form1, but I can't seem to access startTimer() through f1.

What would be the best approach to solve this?
Posted
Updated 30-Aug-14 16:26pm
v2
Comments
[no name] 30-Aug-14 22:30pm    
That's because you would need to use f1 not form1
kmllev 30-Aug-14 22:33pm    
Yes, and I've tried it, but for some reason, when I type f1.startTimer(); I get an error saying 'System.Windows.Forms.Form' does not contain a definition for 'startTimer' and no extension method 'startTimer' ......
[no name] 30-Aug-14 22:36pm    
Well it is most likely not lying to you. You need to review your architecture.
kmllev 30-Aug-14 22:50pm    
That's the problem, I'm just beginning to learn C# and I can't seem to find what's wrong.

1 solution


  1. Don't pass an instance of Form1 to Form2.
  2. Rewrite btnPause_Click() like so:
    private void btnPause_Click(object sender, EventArgs e)
    {
        timer.Stop();              // stop the timer
        new Form2().ShowDialog();  // show Form2 and wait until the user closes it
        timer.Start();             // restart the timer
    }

/ravi
 
Share this answer
 
Comments
kmllev 31-Aug-14 0:32am    
I can't believe it's that simple. Gah I complicate things a lot. Thank you!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900