How do you access the name of the image in a picturebox in Visual Studio using C#

前端 未结 4 1516
花落未央
花落未央 2020-12-12 02:35

I have a program which has 16 grid tiles using picturebox but only uses 5 images, the rest of the tiles are just a black image.

I would like to be able to tell which

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 03:10

    You can do something like this using the Tag property like @Adriano suggested:

    public Form1()
    {
        InitializeComponent();
        pictureBox1.Click += pictureBox_Click;
        pictureBox2.Click += pictureBox_Click;
        pictureBox3.Click += pictureBox_Click;
        // ...
        pictureBox1.Tag = "picture1.png";
        pictureBox2.Tag = "picture2.png";
        pictureBox3.Tag = "picture3.png";
    }
    
    void pictureBox_Click(object sender, EventArgs e)
    {
        PictureBox pb = sender as PictureBox;
    
        if (pb.BackColor != Color.Black)
            Debug.WriteLine(pb.Tag.ToString());
        else
            Debug.WriteLine("Black image");
    
    }
    

提交回复
热议问题