FlashCards Language Program : How to read and save Images in a Sql Server Database using ADO.NET | ||||||
| ||||||
Figure 1 - Flashcards read in from a Sql Database Source Code: FlashCardsMG.zip I thought it would be fun to write a simple program that displayed flashcards from a database and at the same time, show you how to read and write images to the database. This program is a simple flashcard program that talks to a single table in a Sql Server Database. The design of the database table is shown below:
Figure 2 - FlashCard DB Design Reverse Engineered Using WithClass 2000 The Picture field is of type varbinary. As seen from the database design diagram, it holds 8000 bytes of data, enough for a square picture of about 89 x 89 pixels. When I created the table using the Server Explorer wizard, I needed to specifiy the maximum length in order to get the image storage to work correctly. Although the database is not provided with the download, you can easily recreate it using the design diagram above. Below is also a snapshot from server explorer of the data:
Figure 3 - Snapshot from the Server Explorer of the Data in this sample
Alot of the coding for this example is done visually. I created the sql server adapter and sql connection simply by dragging the table from the server explorer into the Design View of the Form. At this point, you have almost everything you need to read the flashcard information into the Form. The code for reading in the table in Figure 3 is shown in the listing below:
Reading in the byte data is as simple as assigning the DataRow Picture Column to a byte array. Once we have the byte array, we can use it to create an image file (in this program we use gif format, although you are free to change it to use your own). The FileStream class serves our purpose well here, because it can be used to create a file from byte data. Once we've created the temporary gif file on our disk, we can assign it to the picturebox component. Writing Image Data into the Database is almost as easy. In this application, we've created a second form used to populate the database. This form serves as almost a modeless dialog to allow us to put our flashcards easily into the Sql Server Database:
Figure 4- Second Form used to Populate the Database The Code for writing to the Database is shown below:
The code above for writing a picture to the database is very similar to reading, only performed in the opposite direction. First you read the data into a byte array using the FileStream class. Then you assign the DataRow Picture Item to the byte array data that you just read. Finally, call Update on the Adapter to force it to write the picture data (along with the textual data) out to the database. Improvements One thing that would be nice to do in this program is to allow for font changes and store the font information in the database. This way you could adapt this program to work with any language and any language character set.
|