在不知道其名称的情况下更改发件人对象的属性

时间:2011-03-09 11:53:10

标签: c# .net winforms

我正在尝试更改网格中PictureBox的BackColor。 PictureBox是数组的一部分,数组有一个chared事件处理程序。我无法根据点击哪一个来更改不同的PictureBox。

这是我到目前为止所做的:

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>

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

事件处理程序的sender参数是引发事件的实例。这是用户点击的PictureBox实例。如果要更改其BackColor,只需将发送方对象转换为正确的类型并设置新颜色。

private void picturebox_Click(object sender, EventArgs e)
{
    var pictureBox = sender as PictureBox;
    if (pictureBox != null) {
        pictureBox.BackColor = Color.Blue;
    }
}

答案 1 :(得分:0)

在事件处理程序上,sender包含导致事件处理程序触发的对象。因此,通过将其转换为正确的类型,我们可以按照以下示例访问所有属性:

private void picturebox_Click(object sender, EventArgs e)
{
     PictureBox pic = (PictureBox)sender;
     MessageBox.Show(pic.Name);
}

注意:代码未经测试,无法访问VS以进行测试