Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Im trying to start timer and changing backcolor of button (from static method). I tried this code but it didnt work :

What I have tried:

Application.OpenForms.OfType<form1>().Last().buttonName.BackColor = Color.LimeGreen; //Button Back Color

Application.OpenForms.OfType<form1>().Last()?.timerName.Start();
// Starting Timer

Application.OpenForms.OfType<form1>().Last().timerName.Interval = 1000;
// Changing Timer Interval
Posted
Updated 18-Apr-20 6:11am
Comments
[no name] 18-Apr-20 11:51am    
"but it didnt work" means? Any error/exception message?

Or maybe simply the form does not exists and you fail here?
Application.OpenForms.OfType<form1>()?.Last().buttonName.BackColor = Color.LimeGreen;
and here
Application.OpenForms.OfType<form1>().Last()?.timerName.Interval = 1000;
Member 14782009 18-Apr-20 12:14pm    
just nothing happened, and it gives an error when i put "?"
[no name] 18-Apr-20 12:23pm    
And it gives error... pleeeaaase, the error is what?
BillWoodruff 18-Apr-20 12:14pm    
set the Timer interval before calling 'Start

as OxO1AA asks:L describe the error
[no name] 18-Apr-20 12:31pm    
"set the Timer interval before calling Start"
Good catch, I missed that one

1 solution

basically, don't use a static method. You need an instance of a form, make the method a member of that form and use the instance that provides.

If you are trying to do this from a different form then you shouldn't - you are making that for (or static code) far, far too aware of the mechanics of how Form1 works, and that's a very bad idea.
Instead, you should be using events to get Form1 to deal with it itself (if it chooses to). That way, OOPs is satified and your code becomes a lot more maintainable.

Exactly how depends on the "relationship" between the two forms.
Have a look at these, one of them will fit your circumstances.
The form that creates an instance of another:
C#
MyForm mf = new MyForm();
mf.Show();
Is the "parent", the other form is the "child".
(This doesn't imply any formal MDI relationship)

Transferring information between two forms, Part 1: Parent to Child[^]
Transferring information between two forms, Part 2: Child to Parent[^]
Transferring information between two forms, Part 3: Child to Child[^]
 
Share this answer
 

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