简体   繁体   中英

adding an action for click event on picturebox in c#

I get a pictureboxe and try to add it an action to change background Image upon click event happen, but there is no action. So, this is the code:

pieces bishopBB = new pieces();        
public Form1()
        {              
         // object of picturebox
            bishopBB.Location = new Point(300, 455);
            bishopBB.Parent = this;
            bishopBB.Click += new System.EventHandler(pictureboxes_Click)
            InitializeComponent();
        }
private void pictureboxes_Click(object sender, EventArges e)
       {
            backgroundImage = Properties.Resources.black;
       }

To change the current image of the PictureBox control, you need to refer to the control and reference the BackgroundImage property (not 'backgroundImage'):

   private void pictureboxes_Click(object sender, EventArges e)
   {
        this.pictureboxes.BackgroundImage = Properties.Resources.black;
   }

To change the background image of the form:

    private void pictureboxes_Click(object sender, EventArgs e)
    {
        this.BackgroundImage = Properties.Resources.black;
    }

To do this you can use the on_click property of the picturebox. You can then use the like picbox.image = whatever the image location is

Looking at the name and other indicators I would assume (and hope) that pictureboxes_Click is a common click handler for many PictureBoxes .

So to access the one that has been clicked you need to cast sender to PictureBox and then set the BackgroundImage :

private void pictureboxes_Click(object sender, EventArges e)
{
   ((PictureBox)sender).BackgroundImage = Properties.Resources.black;
}

I'm a little amazed though that your spelling of backgroundImage compiles. The correct spelling BackgroundImage refers to the current class, usually the Form and it should also show, unless your Form has a black background already..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM