0

I have two buttons in my view and one picture box. I want to design a code such that the picture box displays images in a directory and after clicking either of the two buttons it displays the next image. Basically, it should wait for user to click the button.

This is snapshot of my view

This is the sample code. Please help me.

 foreach (string file in Directory.EnumerateFiles(sourcePathImages, "*.jpg"))
        {

            Image loadedImage = new Bitmap(file);
            if (loadedImage != null)
            {
                pictureBox1.Image = loadedImage;
                filename.Text = filenames[counter];
                label.Text = labels[counter++];
            }

        }

What to add in the foreach loop so that my code waits until either of the two buttons is pressed.

  • 3
    It is incorrect not to mention inefficient for code to loop around waiting for a button click. Read up on _events_ –  Jun 12 '17 at 04:20
  • Have the list of files stored and do the change of the image in the button handler instead. – Paweł Łukasik Jun 12 '17 at 04:20
  • Images should be uploaded using image button – Alex78191 Jun 12 '17 at 04:33
  • That's what `Click` events are for... – Rufus L Jun 12 '17 at 04:35
  • Taking your question literally you can use `async`/`await` to do what you're asking. See marked duplicates. But also note [this answer](https://stackoverflow.com/a/32836619) which suggests that you simply discard the explicit loop, and use a non-static field to track the state that the loop would otherwise maintain, updating it as desired on each button click. – Peter Duniho Jun 12 '17 at 04:36

1 Answers1

0

You can convert Directory.EnumerateFiles to List and keep index of the current image name. Or you can use GetFiles() method to get array of names.

Alex78191
  • 2,383
  • 2
  • 17
  • 24
  • There are 5000 image files, so it's not effecient to load them all at once. Plus, I want to make my code wait until user presses one of the two buttons. As soon as user presses one of the two buttons the picture box should display the next image and the same process to go on. – yashfujifilm Jun 12 '17 at 04:30
  • @yashfujifilm Only file names are loaded – Alex78191 Jun 12 '17 at 04:31
  • I already have the file names stored in an array. My problem is to make it wait for user clicking input nothing else. – yashfujifilm Jun 12 '17 at 04:32
  • @yashfujifilm You don't know about Click event? Just double click on button in designer and method for event will be created. – Alex78191 Jun 12 '17 at 04:34
  • Thank you. The above answer kinda worked. – yashfujifilm Jun 12 '17 at 08:13