9.11. Reading and Writing Binary Data with SQL Server
Problem
You need to read and write binary data from and to a SQL Server 2000 database.
Solution
Use the techniques from the following example.
The schema of table TBL0911 used in this solution is shown in Table 9-3.
Table 9-3. TBL0911 schema
Column name |
Data type |
Length |
Allow nulls? |
---|---|---|---|
Id |
|
4 |
No |
Description |
|
50 |
Yes |
BlobData |
|
16 |
Yes |
The sample code contains nine event handlers:
Form.Load
Creates a
DataAdapter
to read and update the Id and Description fields from table TBL0911. ATextBox
is bound to the Id column and anotherTextBox
is bound to the Description field. ADataSet
is filled with all records from TBL0911. TheBindingManager
is retrieved for the table in theDataSet
. A handler is attached to theBindingManager.PositionChanged
event. Finally, the display is updated for the current record in the table.BindingManagerBase.PositionChanged
Clears the image displayed in the
PictureBox
on the form. The ID of the current record is retrieved. A connection is created to select the field BlobData—an image—from TBL0911 corresponding to the current record. Theimage
is retrieved using aDataReader
. AMemoryStream
is created from the image retrieved and theMemoryStream
is loaded into thePictureBox
using theImage.FromStream( )
method passing the image in theMemoryStream
as an argument.- Select Image
Button.Click
Opens a file dialog to allow an image to be selected by the user. The
image
is retrieved using aFileStream ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.