Search This Blog

Friday, April 2, 2010

Store image in Sql Server from Windows Forms

To Store the Image in Sql Server database from Windows forms.


This concept can be used,to store the image as image data we need a column that has datatype image which stores pictures as binary data .then from Windows Form we create a byte array using the BinaryWriter then in SqlCommand object we pass the byte array created by BinaryWriter to column. I am giving an example here which stores an image follow these steps in your example-

first create a table with following structure:

CREATE TABLE imageTable
(
imgId int IDENTITY(1,1),
imgSrc VARCHAR(100),
imgData IMAGE
)

Then design a windows form having these controls and with following properties:
1.TextBox Name:-textBox1
2.Button-Name=button1,Text:=Browse
3.Button-Name=button2,Text=Save

use the Namespace System.Io to use the class Stream and BinaryReader
using System.Io;

On the Click Event of Browse button write this code

void button1_click(object sender,EventArgs e)
{
OpenFileDialog dlg=new OpenFieDialog();
if(dlg.ShowDialog()!=DialogResult.Cancel)
{
textBox.Text=dlg.FileName;
}
}

On the Save Button Click Event Write the code to create byte array and insert it to database

void button2_Click(object sender,EventArgs e)
{
byte []data=null;
FileStream stream=new FileStream(textBox1.Text);
int length=(int)stream.Length;
data=new byte[length];
BinaryWriter bw=new BinaryWriter(stream);
data=(byte[])bw.WriteBytes(length);
Sqlconnection con=new SqlConnection("your connecion string");
con.Open();
SqlCommand cmd=new SqlCommand("insert into imageTable values(@source,@pic)",con);
cmd.Parameters.AddWithValue("source",textBox1.Text);
cmd.Parameters.AddWithValue("pic",data);
cmd.ExecuteNonQuery();
MessageBox.Show("Your Image Saved ","save");
}
Hope this example will help.

1 comment: