views:

118

answers:

3

My plan is to create a single event that will go:

"Ok, the mouse entered a registered pictureBox, load X picture onto it according the name of sender."

What is the best way to handle this?

Should I create a dictionary with the name as key, and the location of the picture resource as the value?

Here's what I have so far:

private void SetPictureBoxEvents()
        {
            Andromeda.MouseEnter += new EventHandler(HeroMouseEnter);
            Engineer.MouseEnter += new EventHandler(HeroMouseEnter);
            Nighthound.MouseEnter += new EventHandler(HeroMouseEnter);
            Swiftblade.MouseEnter += new EventHandler(HeroMouseEnter);
        }

void HeroMouseEnter(object sender, EventArgs e)
    {
        //My picture box is named Andromeda. I'm going use that name 
        // as a key is a Dictionary and pull the picture according to the name.
        //This is to make a generic event to handle all movements.
        //Any help?
        // ((PictureBox)sender).Image =             
    }

How could I also create a dictionary for image locations in my Resources.:

Dictionary<string, TestProject.Properties.Resources> HeroList 
       = new Dictionary<string, TestProject.Properties.Resources>();

This isn't working.

A: 

Typically I would see a switch statement used for this.

Inside your HeroMouseEnter method

PictureBox sendingBox = (PictureBox)sender;
Switch(sendingBox.Name)
{
    case "MyPicture":
        //Set picture here
        break;
    case "MyPicture2":
        //Next picture....
        break;
}

Also, if your images are in resources already, it is more than likely more wasteful to try and create a dictionary for the images, as that is just duplication.

Mitchel Sellers
A: 

Make your own event handler class which has an instance variable corresponding to the image name. Then your code would look like...

private void SetPictureBoxEvents()
    {
        Andromeda.MouseEnter += new EventHandler(new HeroMouseHandler("Andromeda.jpg").HeroMouseEnter);
        Engineer.MouseEnter += new EventHandler(new HeroMouseHandler("Engineer.jpg").HeroMouseEnter);
        Nighthound.MouseEnter += new EventHandler(new HeroMouseHandler("Nighthound.jpg").HeroMouseEnter);
        Swiftblade.MouseEnter += new EventHandler(new HeroMouseHandler("Swiftblade.jpg").HeroMouseEnter);
    }

Or better yet, you would pass the hero itself in (instead of the string) and the class would know how to translate from a hero to a corresponding image.

Pace
+4  A: 

You already did it. Almost - see below

void HeroMouseEnter(object sender, EventArgs e)
{
    //My picture box is named Andromeda. I'm going use that name 
    // as a key is a Dictionary and pull the picture according to the name.
    //This is to make a generic event to handle all movements.
    //Any help?
    ((PictureBox)sender).Image =  GetImage(((PictureBox)sender).Name)           
}
mfeingold