Search code examples
c#picturebox

Loaded pictureBox.ImageLocation is null


I'm trying to do something when I click image displayed inside pictureBox1. pictureBox is loaded with this code:

string imgpath = @"img\256.png";
pictureBox48.Image = Image.FromFile(imgpath);

Then control is released to me so I can see that the picture loaded correctly. Then i click the picture:

public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}

This doesn't work. When I debug the code I see that variable1 stay null, that is pictureBox48.ImageLocation is null. Why is that? Shouldn't it be the path to the image that is assigned there?


Solution

  • You can't get the image path when you set the image using the Image property because you are assigning an Image object which can come from different sources.

    Set the image using ImageLocation.

    string imgpath = @"img\256.png";
    pictureBox48.ImageLocation = imgpath;
    

    When you click in the PictureBox you can get the path using the same property:

    public void pictureBox48_Click(object sender, EventArgs e)
    {
        string variable1 = pictureBox48.ImageLocation;
        Form3 fo = new Form3(variable1);
        fo.ShowDialog();
    }