// Display the image saved in SQL Server in picture
Private void listbox1_selectedindexchanged (Object sender, system. eventargs E)
{
Byte [] buffbyte = NULL;
String comm = @ "select IMG from Table1 where id =" + this. listbox1.selectedvalue;
This. sqlcommand1 = new system. Data. sqlclient. sqlcommand ();
This. sqlcommand1.commandtype = system. Data. commandtype. text;
This. sqlcommand1.commandtext = comm;
This. sqlcommand1.connection = This. sqlconnection1;
This. sqlconnection1.open ();
System. Data. sqlclient. sqldatareader RD = This. sqlcommand1.executereader ();
While (RD. Read ())
{
Buffbyte = (byte []) RD [0]);
}
Rd. Close ();
This. sqlconnection1.close ();
// Put the byte array of the image into the memory stream
System. Io. memorystream MS = new system. Io. memorystream (buffbyte );
// Create bitmap through stream object
System. Drawing. bitmap BMP = new Bitmap (MS );
This. picturebox1.image = BMP;
}
// Save the image to the image field of SQL Server
Private void button2_click_1 (Object sender, system. eventargs E)
{
String pathname;
If (this. openfiledialog1.showdialog () = system. Windows. Forms. dialogresult. OK)
{
Pathname = This. openfiledialog1.filename;
System. Drawing. Image IMG = system. Drawing. image. fromfile (pathname );
This. picturebox1.image = IMG;
// Read the image into a byte array
System. Io. filestream FS = new system. Io. filestream (pathname, system. Io. filemode. Open, system. Io. fileaccess. Read );
Byte [] buffbyte = new byte [fs. Length];
FS. Read (buffbyte, 0, (INT) fs. Length );
FS. Close ();
FS = NULL;
// CREATE Command
String comm = @ "insert into Table1 (IMG, name) values (@ IMG, @ name )";
This. sqlcommand1 = new system. Data. sqlclient. sqlcommand ();
This. sqlcommand1.commandtype = system. Data. commandtype. text;
This. sqlcommand1.commandtext = comm;
This. sqlcommand1.connection = This. sqlconnection1;
// Create a parameter
This. sqlcommand1.parameters. Add ("@ IMG", system. Data. sqldbtype. Image );
This. sqlcommand1.parameters [0]. value = buffbyte;
This. sqlcommand1.parameters. Add ("@ name", system. Data. sqldbtype. varchar );
This. sqlcommand1.parameters [1]. value = pathname. substring (pathname. lastindexof ("
// ") + 1
);
Try
{
This. sqlconnection1.open ();
This. sqlcommand1.executenonquery ();
This. sqlconnection1.close ();
}
Catch (system. Exception ee)
{
MessageBox. Show (EE. Message );
}
Buffbyte = NULL;
This. filllistbox ();
}
}
Source: http://blog.codelphi.com/miracle/articles/6053.aspx? Pending = true