Search code examples
c#picturebox

C# How to combine the picturebox click event to the corresponding function?


C# How to combine the picturebox click event to the corresponding function?

private void pbx_process(int i) 
{ 
   PictureBox picture_box 
      = this.Controls.Find("pbx_image" + i, true).FirstOrDefault() 
        as PictureBox; 
   if (picture_box.Image != null) pbx_image.Image = picture_box.Image; 
   else pbx_image.Image = null; 
} 

private void pbx_image1_Click(object sender, EventArgs e) 
{ 
    pbx_process(1); 
}

private void pbx_image2_Click(object sender, EventArgs e) 
{ 
    pbx_process(2); 
}

private void pbx_image3_Click(object sender, EventArgs e) 
{ 
    pbx_process(3); 
}

i want to make these simple. Please help....


Solution

  • create a function like this

    AddEvent()
    {
    pbx_image1.click+=pbx_image_Click;
    pbx_image2.click+=pbx_image_Click;
    pbx_image3.click+=pbx_image_Click;
    }
    

    then

    private void pbx_image_Click(object sender, EventArgs e) 
    { 
    
        pbx_process(sender as PictureBox); or you can do the process right here
    }
    

    and then

    private void pbx_process(PictureBox pictureBox) 
    { 
    
       if (pictureBox.Image != null) pbx_image.Image = pictureBox.Image; 
       else pbx_image.Image = null; 
    } 
    

    remember to call AddEvent function once your form is loaded to add events to picture boxes.