Reputation: 5594
I am getting a list of pictures from a directory and storing the filenames in a List<String>
. I then loop through each of these and create a PictureBox
for each of them, I then add the same click event to each. The controls are in a FlowLayoutPanel
foreach(String file in this._files){
PictureBox box = new PictureBox();
box.Height = 50;
box.Width = 50;
box.ImageLocation = file;
box.SizeMode = PictureBoxSizeMode.Zoom;
box.Click += this.PictureClick;
this.flowLayoutPanel1.Controls.Add(box);
}
private void PictureClick(object sender, EventArgs e){
// how do I get the one that has been clicked and set its border color
}
How do I get the one that has been clicked and set its border color?
Upvotes: 0
Views: 4451
Reputation: 8469
The sender
parameter is indeed your PictureBox
, downcast to object. Access it this way:
var pictureBox = sender as PictureBox;
Drawing a border around it could not be so easy as you will have to either override the OnPaint
method of the PictureBox, either handle the Paint
event.
You can use this class to draw a black thin border around your image.
public class CustomBorderPictureBox : PictureBox
{
public bool BorderDrawn { get; private set; }
public void ToggleBorder()
{
BorderDrawn = !BorderDrawn;
Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (BorderDrawn)
using (var pen = new Pen(Color.Black))
pe.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1);
}
}
Upvotes: 2
Reputation: 1436
sender
is the PictureBox
that was clicked:
private void PictureClick(object sender, EventArgs e) {
PictureBox oPictureBox = (PictureBox)sender;
// add border, do whatever else you want.
}
Upvotes: 5