Search code examples
c#pictureboximageopenfiledialog

Show default picture from a picture box before opening a file dialog


Basically, I have a browse button to open a file dialog and fetch the picture into a textbox and picturebox. However, I want to have a default picture that shows (like facebook default profile picture) before the user opens the file dialog. When the user opens the file dialog, chooses a picture and clicks OK, the default picture will be changed into the selected picture. If the user clicks Cancel, the default picture won't change.

My question:

  1. Where should I put the default picture? (in a folder the same path with the .SLN or anywhere else)?
  2. What should I code to show the default picture in my picture box?

Here's my following code:

private void buttonbrowse_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "image files|*.jpg;*.png;*.gif";
    DialogResult dr = ofd.ShowDialog();

    if (dr == DialogResult.Cancel)
        return;

    pictureBoxPhoto.Image = Image.FromFile(ofd.FileName);
    textBoxPhoto.Text = ofd.FileName;

}

Solution

    1. I would advise to add your picture into your project Resources:

      Visual Studio screenshot

      It will then be stored into the Resources folder of your project:

      Visual Studio screenshot

    2. You can then add it to your picturebox in your form constructor:

      public Form1() {
          InitializeComponent();
          pictureBox1.Image = Properties.Resources.DefaultPicture;
      }