Introduction
In this article, I am going to explain how to use a PictureBox on a Windows. Forms app using Visual Studio 2017.
Step 1. Start the Project
Let's create a new project using Visual Studio 2017.
Select New Project--->Visual C#-->Windows Forms App (.NET Framework), give your project a name and click OK.
This action creates a WinForms project with a default form and you should see the Windows Designer.
Step 2. Drag and Drop Control
Let's add a PictureBox control to the form by dragging it from Toolbox and dropping it into the form. You will see that PictureBox 1 is added to the form. This control is now available to you in the code behind.
Additional control
Now, let's add another control to the form by dragging the other control from the Toolbox to the form. Drag and drop openFileDialog, saveFileDialog and button control from Toolbox. You can also change the properties of the other controls.
PictureBox
The PictureBox control is used for displaying images on the form. The Image property of the control allows you to set an image both at design time or at runtime.
Properties of PictureBox
- AllowDrop Property: Specifies whether the picture box accepts data that a user drags on it.
- ImageLocationProperty: Gets or sets the path or the URL for the image displayed in the control.
- InitialImage Property: Gets or sets the image displayed in the control when the main image is loaded.
- WaitOnLoad Property: Specifies whether or not an image is loaded synchronously.
Step 3. Coding for Button Click Event
You can add a button-click event handler by simply double-clicking on the button control event handler. We can open and save the picture using saveFileDialog and openFileDialog.
public partial class Form1 : Form
{
Image file;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "JPG (*.JPG)|*.jpg";
if (f.ShowDialog() == DialogResult.OK)
{
file = Image.FromFile(f.FileName);
pictureBox1.Image = file;
}
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
f.Filter = "JPG (*.JPG)|*.jpg";
if (f.ShowDialog() == DialogResult.OK)
{
file.Save(f.FileName);
}
}
}
Step 4. Compile and Run
Now, simply compile and run the application. Click the open button. Choose the image from the local disk and it will be displayed in the PictureBox.
Now, click and save the button. The picture will be saved to the disk in the local folder.
Summary
In this article, you saw how to use a PictureBox control. Hope you found this article interesting. For any feedback, please post it as a comment at the bottom of this article. Thank you!.