Reputation: 120
I am trying to change the BackColor of a PictureBox in a grid. The PictureBox is part of an array and the array has a chared event handler. I am having difficulty changing different PictureBox's depending on which one is clicked.
This is what I have so far:
private PictureBox[,] GameGrid = new PictureBox[20, 20];
public frmGame() { int x = 10; int y = 10; for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { GameGrid[i, j] = new System.Windows.Forms.PictureBox(); setUpPicBox(x, y, i, j); x += 11; } y += 11; x = 10; } InitializeComponent(); } public void setUpPicBox(int x, int y, int i, int j) { this.GameGrid[i, j].Location = new System.Drawing.Point(x, y); this.GameGrid[i, j].Size = new System.Drawing.Size(10, 10); this.GameGrid[i, j].BackColor = Color.Black; this.GameGrid[i, j].Name = "btnGrid" + i + "-" + j; this.GameGrid[i, j].Visible = true; this.GameGrid[i, j].CreateGraphics(); this.GameGrid[i, j].Click += new System.EventHandler(this.picturebox_Click); this.Controls.Add(GameGrid[i, j]); } private void picturebox_Click(object sender, EventArgs e) { }</code>
Any help would be appreciated
Upvotes: 0
Views: 4953
Reputation: 3772
On your event handler, sender contains the object that caused the event handler to fire. So by casting it to the correct type, we can then access all the properties as per this example:
private void picturebox_Click(object sender, EventArgs e)
{
PictureBox pic = (PictureBox)sender;
MessageBox.Show(pic.Name);
}
Note: code untested, not got access to VS to test
Upvotes: 0
Reputation: 3419
The event handler's sender
parameter is the instance that raised the event. Here it is the PictureBox instance that the user has clicked. If you want to change its BackColor, you just cast the sender object to correct type and set the new color.
private void picturebox_Click(object sender, EventArgs e)
{
var pictureBox = sender as PictureBox;
if (pictureBox != null) {
pictureBox.BackColor = Color.Blue;
}
}
Upvotes: 3