How to save images to a database:
Public void imgtodb (string SQL)
{// The imge variable name required to be saved in the parameter SQL is @ Images
// Call method such as imgtodb ("Update userphoto set photo = @ images where userno = '" + temp + "'");
Filestream FS = file. openread (t_photo.text );
Byte [] imageb = new byte [fs. Length];
FS. Read (imageb, 0, imageb. Length );
FS. Close ();
Sqlcommand com3 = new sqlcommand (SQL, con );
Com3.parameters. Add ("@ images", sqldbtype. Image). value = imageb;
If (com3.connection. State = connectionstate. Closed)
Com3.connection. open ();
Try
{
Com3.executenonquery ();
}
Catch
{}
Finally
{Com3.connection. Close ();}
}
Read the image in the database and display it in picturebox:
Method 1:
Private void showimage (string SQL)
{
// Call method such as showimage ("select photo from userphoto where userno = '" + userno + "'");
Sqlcommand cmd = new sqlcommand (SQL, Conn );
Conn. open ();
Byte [] B = (byte []) cmd. executescalar ();
If (B. length> 0)
{
Memorystream stream = new memorystream (B, true );
Stream. Write (B, 0, B. Length );
Picturebox1.image = new Bitmap (Stream );
Stream. Close ();
}
Conn. Close ();
}
Method 2: select a row in DG:
Private void dg_mouseup (Object sender, mouseeventargs E)
{
// Select the entire row
If (E. Button = system. Windows. Forms. mousebuttons. Left)
{// User ID, name, gender, ID card number, nationality, school, department, campus, department, phone number, photo
// Display the photo
Object imgobj = DG [10, dg. currentrow. Index]. value;
If (imgobj! = NULL &&! Convert. isdbnull (imgobj ))
{
Byte [] imgb = (byte []) imgobj;
Memorystream memstream = new memorystream (imgb );
Try
{
Bitmap myimge = new Bitmap (memstream );
This. picturebox1.image = myimge;
}
Catch
{
DB. msgbox ("An error occurred while reading photos from the database! ");
}
}
Else
Picturebox1.image = NULL;
}
}