John
John

Reputation: 3050

Change pictureBox1 properties in Timer method

So I have this awesome pictureBox1 in my C# program. Every 5 second I call an time method like this:

public Form1()
{
    InitializeComponent();
    aTimer = new System.Timers.Timer(10000);
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 2000;
    aTimer.Enabled = true;
}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{ 
}

I am trying to change a property of a pictureBox object I got. But I get this error when trying to do so:

Error 1 An object reference is required for the non-static field, method, or property 'Simma.Form1.pictureBox1' C:\Users\John\Desktop\Simma\Simma\Form1.cs 39 13 Simma

The pictureBox1 is set to Public though.

Upvotes: 0

Views: 166

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500695

The problem must be in the code you haven't shown us... presumably in OnTimedEvent.

The simplest fix is to make OnTimedEvent an instance method instead. This isn't a matter of accessibility (and the field shouldn't be public - make it private!) it's a matter of trying to use an instance field from a static method.

Note, however, that you also shouldn't try to access a UI element from a non-UI thread. Currently your timer will fire its event in a different thread, causing cross-thread issues.

The simplest fix for this is to use a System.Windows.Forms.Timer instead of a System.Timers.Timer.

Upvotes: 1

Related Questions