This documentation is archived and is not being maintained.

Setting Pictures at Run Time (Windows Forms)

Visual Studio .NET 2003

You can programmatically set the image displayed by a Windows Forms PictureBox control.

To set a picture programmatically

  • Set the Image property using the FromFile method of the Image class.

    In the example below, the path set for the location of the image is the My Documents folder. This is done, because you can assume that most computers running the Windows operating system will include this directory. This also allows users with minimal system access levels to safely run the application. The example below assumes a form with a PictureBox control already added.

    ' Visual Basic
    Private Sub LoadNewPict()
       ' You should replace the bold image 
       ' in the sample below with an icon of your own choosing.
       PictureBox1.Image = Image.FromFile _
       (System.Environment.GetFolderPath _
       (System.Environment.SpecialFolder.Personal) _
       & "\Image.gif")
    End Sub
    
    // C#
    private void LoadNewPict(){
       // You should replace the bold image 
       // in the sample below with an icon of your own choosing.
       // Note the escape character used (@) when specifying the path.
       pictureBox1.Image = Image.FromFile
       (System.Environment.GetFolderPath
       (System.Environment.SpecialFolder.Personal)
       + @"\Image.gif");
    }
    
    // C++
    private:
       void LoadNewPict()
       {
          // You should replace the bold image 
          // in the sample below with an icon of your own choosing.
          pictureBox1->Image = Image::FromFile(String::Concat(
             System::Environment::GetFolderPath(
             System::Environment::SpecialFolder::Personal),
             "\\Image.gif"));
       }
    

To clear a graphic

  • First, release the memory being used by the image, and then clear the graphic. Garbage collection will free up the memory later if memory management becomes a problem.
    ' Visual Basic
    If Not (PictureBox1.Image Is Nothing) Then
       PictureBox1.Image.Dispose()
       PictureBox1.Image = Nothing
    End If
    
    // C#
    if (pictureBox1.Image != null) 
    {
       pictureBox1.Image.Dispose();
       pictureBox1.Image = null;
    }
    
    // C++
    if (pictureBox1->Image != NULL)
    {
       pictureBox1->Image->Dispose();
       pictureBox1->Image = NULL;
    }
    
    Note   For more information on why you should use the Dispose method in this way, see Cleaning Up Unmanaged Resources.

    This code will clear the image even if a graphic was loaded into the control at design time.

See Also

Introduction to the Windows Forms PictureBox Control | PictureBox Class | Loading a Picture at Design Time (Windows Forms) | Modifying the Size or Placement of a Picture at Run Time (Windows Forms) | Image.FromFile Method | PictureBox Control (Windows Forms)

Show: