Filling a PictureBox from a File
In the previous example, I only considered one possible output: plain text. But you can design controls that accept a variety of data types. For example, the TextBox can be further extended to accept a drop from the shell and display the contents of the file. I'll demonstrate this feature for a PictureBox
If you try to set the AllowDrop
property on the PictureBox
control at design-time, you're probably going to have a hard time. For some reason, the property is not listed in the Property Grid, although it's perfectly supported. You must set it using code.
PictureBox1.AllowDrop = True
event handler ensures that the data comes from the shell and contains just one file name.
If Not e.Data.GetDataPresent("FileNameW") Then
e.Effect = DragDropEffects.None
e.Effect = = DragDropEffects.Copy
event handler retrieves the file name and attempts to extract the image in it. Note that at this point, no check has been made on the type of file. It can certainly be a JPEG as well as a TXT or a DOC file. You can filter the file type in the DragOver
event or accept any file and try to render its contents as an image.
|Figure 3. PictureBox Drag/Drop Operation: When you drop a file on an enhanced PictureBox control, a default image (shown on the left here) is applied if the dropped file is not a valid source (for example, if it is not an image file).|
If the file doesn't contain an image, a default image is displayed, as in the leftmost image of Figure 3
Note that if the image you assign to the PictureBox's Image
property is not a valid object (that is, the source file is not a graphic file), an exception is thrown. Furthermore, it is important that you explicitly open and close the source file. To minimize coding, you could resort to the following.
PictureBox1.Image = bmp.FromFile(fileName)
The functional effect is the same, but a significant drawback is just around the corner. The image file results lock (don't respond to changes) until you terminate the application. The sample image, shown when the dropped file is not a valid file, is generated using a bunch of GDI+ code.
Public Function DummyImage() As Image
Dim bmp As New Bitmap(200, 100)
Dim g As Graphics = _ Graphics.FromImage(bmp)
g.DrawString("No Valid Drop.", _
New Font("Impact", 20), _
Brushes.DarkRed, 10, 10)