Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Friday, March 19, 2010

Store image in DataBase and Display in Gridview and picture box

//Cretate table in sql server "storeimage"
Create table storeimage(
name varchar(100),
pics image)

//code in .Net

byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}

SqlConnection con = new SqlConnection("Data source=.;Database=master;user id=;password=; integrated security=sspi;");
SqlCommand cmd;


private void Form1_Load(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("SElect * from storeimage", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}

private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
byte[] imageData;
imageData = ReadFile(textBox1.Text);
cmd = new SqlCommand("Insert into storeimage(name,pics) values('s' ,@OriginalPath)", con);
cmd.Parameters.Add(new SqlParameter("@OriginalPath", (object)imageData));

cmd.ExecuteNonQuery();
con.Close();

}


private void btnbrowse_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;


}


private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >0)
{
object a = dataGridView1.Rows[e.RowIndex].Cells["Pics"].GetType();
if (a.ToString() != "System.DBNull")
{

byte[] imageData = (byte[])dataGridView1 .Rows[e.RowIndex].Cells["pics"].Value;

imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["pics"].Value;
Image newImage;
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);

newImage = Image.FromStream(ms, true);
}
//set picture
pictureBox1.Image = newImage;
}
}
}