Data binding a WinForms PictureBox to a file path or URL

I've seen this question up on the forums, and I thought I'd write up a little sample of how to accomplish this.

First, let's start with a stock console application (just so I don't have to worry about a WinForms designer file).

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace MyPicBind
{
class Program
{
static void Main(string[] args)
{
// We'll add our code here.
}
}
}

We'll start by loading some sample images (or, rather, their paths) into a DataTable. I'll use whatever is in the My Pictures folder.

// Create a DataTable to bind to.
DataTable table = new DataTable("T");
table.Columns.Add("Caption", typeof(string));
table.Columns.Add("FilePath", typeof(string));

// Populate with whatever is in the My Pictures folder.
string[] pictures = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
foreach (string picture in pictures)
{
table.Rows.Add("Some caption about " + Path.GetFileName(picture), picture);
}

Next, we'll create a few controls: a DataGridView to navigate the images, a Label to hold the caption, and a PictureBox to display the image.

Form form = new Form();
DataGridView grid = new DataGridView();
Label label = new Label();
PictureBox pictureBox = new PictureBox();

// Populate the Form controls.
form.Controls.Add(pictureBox);
form.Controls.Add(label);
form.Controls.Add(grid);
form.WindowState = FormWindowState.Maximized;
form.Shown += delegate { grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); };

Now it's time to set up the data bindings. I'm doing this programmatically, although typically this is easier to do with the Visual Studio designer. You'll see that the trick to go from path to displayed image is to bind to the ImageLocation property.

// Setup the grid.
grid.DataSource = table;
grid.Dock = DockStyle.Top;
grid.ReadOnly = true;

// Setup the label with the image caption.
label.AutoSize = true;
label.DataBindings.Add("Text", table, "Caption");
label.Dock = DockStyle.Top;
label.Padding = new Padding(8);

// Setup the PictureBox with the image contents.
pictureBox.DataBindings.Add("ImageLocation", table, "FilePath");
pictureBox.Dock = DockStyle.Fill;
pictureBox.BorderStyle = BorderStyle.Fixed3D;

Finally, let's make this thing run!

Application.Run(form);

And that's pretty much everything that you need. An additional bonus is that if the image is not accessible or not recognized as an image, a little "error" image will show up, similar to what Internet Explorer does.

 

This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.