Durga
Durga

Reputation: 1303

Timer Control Not working

I am showing images in 3 different picture boxes randomly, and using timer control to change them at some fixed interval.

I am getting images displayed randomly when I close application and open it again, but I want the image to appear randomly using timer, but I am not getting why the timer is not working! where am I doing wrong?

Random random = new Random();
List<string> filesToShow = new List<string>();
List<PictureBox> pictureBoxes;
public Form2()
{
    InitializeComponent();
    Timer timer2 = new Timer();       
    pictureBoxes = new List<PictureBox> {
        pictureBox3,
        pictureBox4,
        pictureBox5
    };
    //ShowRandomImages();
    // Setup timer
    timer2.Interval = 1000; //1000ms = 1sec
    timer2.Tick += new EventHandler(timer2_Tick);
    timer2.Start();
}

private void ShowRandomImages()
{
    foreach (var pictureBox in pictureBoxes)
    {
        if (!filesToShow.Any())
            filesToShow = GetFilesToShow();
        int index = random.Next(0, filesToShow.Count);
        string fileToShow = filesToShow[index];
        pictureBox.ImageLocation = fileToShow;
        filesToShow.RemoveAt(index);
    }
}

private List<string> GetFilesToShow()
{
    string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\StudentModule\StudentModule\Image";
    return Directory.GetFiles(path, "*.jpg", SearchOption.TopDirectoryOnly).ToList();
}

private void timer2_Tick(object sender, EventArgs e)
{
    if (sender == timer2)
    {
        //Do something cool here
        ShowRandomImages();
    }

}

Upvotes: 0

Views: 716

Answers (1)

Grant Thomas
Grant Thomas

Reputation: 45083

if (sender == timer2) ... timer2 does not exist in that scope - a compile time error should be preventing your success, unless you have another instance defined at a higher level with the same name, in which case it's not the timer2 in the constructor - i.e. not the one firing the event - that you're comparing.

The quick fix is to remove the type prefix from the timer2 instantiation in the constructor, like so:

timer2 = new Timer();   

Upvotes: 2

Related Questions