简体   繁体   中英

C# : get the file path of picturebox onclick

I have created a function that loops a folder and retrieves each image file and draw a picturebox on the form. Here is the function :

    private void Create_Controls(string Img_path)
    {
        PictureBox p = new PictureBox();
        p.Size = new Size(138, 100);
        p.Location = new Point(6, 6);
        p.BackgroundImage = Image.FromFile(Img_path);
        p.BackgroundImageLayout = ImageLayout.Stretch;

        this.Controls.Add(p);
    }

So what i need to do is : whenever i click on any picturebox on the form , a message popup with the image file path.

So i thought about adding a custom event :

p.Click += delegate { Pop_Up(); };

AND

    private void Pop_Up()
    {
        /* POP UP MESSAGE WITH Picturebox image file path*/
    }

You need to use the property ImageLocation of the PictureBox . The property gets or sets the path or URL for the image to display in the PictureBox.

Just do the following:

p.Click += new EventHandler(Pop_Up);

...

private void Pop_Up(object sender, EventArgs e)
{
  var pb = sender as PictureBox;
  if(pb != null)
    MessageBox.Show(pb.ImageLocation);
}

You could use Tag property for this.

something like this .

private void Create_Controls(string Img_path)
{
  PictureBox p = new PictureBox();
  p.Size = new Size(138, 100);
  p.Location = new Point(6, 6);
  p.Tag  = Img_path;
  p.BackgroundImage = Image.FromFile(Img_path);
  p.BackgroundImageLayout = ImageLayout.Stretch;

  this.Controls.Add(p);
}

private void Pop_Up()
{
   MessageBox.Show(p.Tag);
}

For more on this Go here .

Then along with what HatSoft says, change your Pop_up() method like:

  private void Pop_Up(object sender, EventArgs e)
   {
       MessageBox.Show(((PictureBox)sender).ImageLocation);
   }

But maybe a bit more elegant and checking if it is indeed a PictureBox etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM