Database Reference
In-Depth Information
Build the project, and run it by pressing Ctrl+F5. You should see the results in Figure 17-5.
Figure 17-5.
Displaying images
How It Works
You declare a type,
Images
, to access the database and provide methods for the form components to
easily get and display images. In its constructor, you connect to the database and create a data reader to
handle the result set of a query that retrieves all the images you stored earlier.
// Constructor
public Images()
{
imageConnection = new SqlConnection(@"data source = .\sql2012;
integrated security = true; initial catalog = SQL2012db;");
imageCommand = new SqlCommand(@" select imagefile,imagedata
from ImageTable", imageConnection);
// Open connection and create data reader
imageConnection.Open();
imageReader = imageCommand.ExecuteReader();
}
When the form is initialized, the new code creates an instance of
Images
, looks for an image with
GetRow()
, and, if it finds one, assigns the file name and image to the text box and picture box with the
GetFilename
and
Getlmage
methods, respectively.