I have to write new "control" and I just start to hate myself and C# because I do not understand why this piece of trivial code cannot work.

public partial class TrendViewerControl : Control

    private System.Timers.Timer myTimer;

    public TrendViewerControl()
        {
            Timer myTimer = new Timer();
            myTimer.Interval = TimerDelay;
            myTimer.Tick += new EventHandler(TickTack);

            myTimer.Enabled = !myTimer.Enabled;

            InitializeComponent();
        }

    private void DrawGrid() 
    {
           myTimer ... HERE COMES THE ERROR, myTimer is NULL
    }

I tried the same for any int value, it worked without problem, int variable has been set in constructor and this value could be used in DrawGrid. But if I try the same thing with any object, timer, pen... it just fails. I have got some tutorials but there are exactly same examples of the thing I am trying to do and they work. myTimer is null but the Timer works somehow (I tried it). As if I just cannot have reference to it (what does garbage collector do? by the way). I just try to start with C#, therefore be merciful :)

Edited 3 Years Ago by pyTony: fixed formating

simple
ALWAYS write code AFTER the InitialiseComponent() call. The control does not exist until that code has completed. It is the code the IDE puts in to create the control and all the child controls on it.

Also, i dont know if it was just a mistake on the post but you should be inheriting from UserControl not Control.

This article has been dead for over six months. Start a new discussion instead.