Search code examples
c#imageevent-handlingpaintevent

How to display multiple images on user command?


I need to be able to display a group of images after the user presses a menu on the Gui. I have been trying to use the following code.

 private void imagePalleteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        List<string> Files = this.MyImageCollection.ConvertFileNamesToList();
        foreach (string currtFile in Files)
        {
            Image newImage = Image.FromFile(currtFile);

            // Create rectangle for displaying image.
            Rectangle destRect = new Rectangle(100, 100, 450, 150);

            // Draw image to screen.
            e.Graphics.DrawImage(newImage, destRect);
        }

I think this would work but I get the error:

'System.EventArgs' does not contain a definition for 'Graphics' and no extension method 'Graphics' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)

I tried replaceing EventHandler with PaintEventHandler, but then I get an error here:

this.imagePalleteToolStripMenuItem.Click += new System.EventHandler(this.imagePalleteToolStripMenuItem_Click);

Stating:

No overload for 'imagePalleteToolStripMenuItem_Click' matches delegate 'System.EventHandler'

I also tried changing that line to:

this.imagePalleteToolStripMenuItem.Click += new System.Windows.Forms.PaintEventHandler(this.imagePalleteToolStripMenuItem_Click);

But this too gives an error stating:

Cannot implicitly convert type 'System.Windows.Forms.PaintEventHandler' to 'System.EventHandler'r

*Note:*My over all goal is to invoke a dialog that will display all the images in thumbnail form. So if this is not the correct way to do so, please redirect me


Solution

  • You're confusing the paint event with the click event. If you want something to happen when a user clicks a button, you put that in the click event. What would you be painting to in a button click?

    Instead, design a new form to show your images, on the button click event, gather your images, and give those images to your dialog. Let the dialog worry about displaying them.