Question

How can I use the method ChangeText in my static method timer_Elapsed?

public Load()
{
    InitializeComponent();

    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 1000;

    // I can't transfer parameters here
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
    timer.Start();
}

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    //Its underlined in red. I need a object reference?
    ChangeText(); 
}

public void ChangeText()
{
    label1.Text = label1.Text + ".";
}
Was it helpful?

Solution 2

As first, your method (timer_Elapsed) could not me static, in order to use an instance property (label1)

There is an other problem in your code: Timer create an other thread, an most of windows control properties can be modified only by UI thread. Your code will throw a CrossThreadException. In order to resolve your problem , you should modify your code with this:

if(this.InvokeRequired) {
   BeginInvoke(
       new MethodInvoker(delegate { label.Text+="."; }));
} else {
    label.Text+="."; 
}

Regards

OTHER TIPS

I don't see any reason why timer_Elapsed should be static. So simply remove it.

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    ChangeText(); //Its not underlined anymore, you have an object reference
}

Another way would be to make ChangeText static. But that won't work since you want to set a Label's Text, so you need an instance of the Form anyway.

Make ChangeText a static method.

public static void ChangeText()

Only static methods are called from a static method, Either make your ChangeText() method to static or make your time_Elapsed method to non-static

You cannot call instance methods in static ones without creating an instance first. You have to create an instance of the class this method belongs to. like below:

var instance = new Load();
instance.ChangeText();  

Update: As other answers suggested, you should reconsider defining timer_Elapsed as static.

Hi Can you try like below:

public Load()
{
    InitializeComponent();

    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 1000;

    // I can't transfer parameters here
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
    timer.Start();
}
 private delegate void ChangeLabel();
        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var ChangeLabel = new ChangeLabel(ChangeText);
            this.BeginInvoke(ChangeLabel);

        }
        private void ChangeText()
        {
            label1.Text = label1.Text + ".";
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top