How to Upload and Display Image In PictureBox Using C#

By FoxLearn 7/17/2024 4:22:34 AM   9.87K
To upload and display an image in a PictureBox control in a C# Windows Forms Application, you can follow these steps.

Open your Visual Studio, then create a new Windows Forms Application.

Next, Drag and drop the PictureBox, TextBox, Button controls from your Visual Studio toolbox into your form designer. You can modify your layout as shown below.

How to show image in picturebox in c# using openfiledialog

display image in picturebox in c#

Adding a click event handler to the Upload button allows you to select an image file, then display the image in your PictureBox control.

How to display image in picturebox in c#

private void btnUpload_Click(object sender, EventArgs e)
{
    // Set the filter to allow only image files
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png" })
    {
        //c# open file dialog with image filters
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            //c# display image in picture box  
            pictureBox1.Image = new Bitmap(ofd.FileName);
            //c# image file path  
            txtFileName.Text = ofd.FileName;
        }
    }
}

Use OpenFileDialog to allow the user to select an image file, you can use Filter property allows the user to select only valid image files, then display image in picturebox in c# using path.

Load the selected image into the PictureBox.

In this example, pictureBox1 refers to the PictureBox control, and btnUpload refers to a Button control used to trigger the file selection dialog. When the user clicks the button, it opens a file dialog where they can choose an image file. Once an image is selected, it is loaded into the PictureBox control.

Related