Monday, October 26, 2009

Inserting images into database and retrieving images

public partial class Form1 : Form
{
MemoryStream ms;
DataSet dsRetrieve = new DataSet();
DataSet dsBindData = new DataSet();
string strUrl = "";

private void Form1_Load(object sender, EventArgs e)
{
BLDataSave objBLDataSave=new BLDataSave ();
dsBindData = objBLDataSave.DataBind();
gvDataBind.DataSource = dsBindData.Tables[0].DefaultView;
}

private void btnSave_Click(object sender, EventArgs e)
{
MLDataSave objMLDataSave = new MLDataSave();
objMLDataSave.sno = int .Parse (txtSno.Text);
objMLDataSave.sname = txtSname.Text;
objMLDataSave.classess = int .Parse (txtClass.Text);
ms = new MemoryStream();
pictureBox1.Image.Save(ms,ImageFormat.Jpeg);
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, Convert.ToInt32(ms.Length));
objMLDataSave.photo = data ;
if (btnSave.Text == "Save")
{
BLDataSave objBLDataSave = new BLDataSave();
if (objBLDataSave.DataSave(objMLDataSave) > 0)
{
MessageBox.Show("inserted successfully");
Form1_Load(sender, e);
}
else
MessageBox.Show("insertion failed");
}

}
private void btnRetrieve_Click(object sender, EventArgs e)
{
MLDataSave objMLDataSave = new MLDataSave();
objMLDataSave.id = int.Parse(txtRetrieve.Text);
BLDataSave objBLDataSave = new BLDataSave();
dsRetrieve = objBLDataSave.DataRetrieve(objMLDataSave);
if (dsRetrieve.Tables[0].Rows.Count > 0)
{
txtSno.Text = dsRetrieve.Tables[0].Rows[0]["sno"].ToString();
txtSname.Text = dsRetrieve.Tables[0].Rows[0]["sname"].ToString();
txtClass.Text = dsRetrieve.Tables[0].Rows[0]["class"].ToString();
byte[] logo = (byte[])dsRetrieve.Tables[0].Rows[0]["photo"];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
fs.Write(logo, 0, logo.Length);
fs.Flush();
fs.Close();
pictureBox1.Image = Image.FromFile(strfn);
lblId.Text = dsRetrieve.Tables[0].Rows[0]["id"].ToString();
}
else
{
MessageBox.Show("Entered sno is not available ");
}

btnSave.Text = "Update";
}
private void btnbrowse_Click(object sender, EventArgs e)
{
OpenFileDialog opg = new OpenFileDialog();
opg.Title = "Select Image";
opg.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG)|*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG*";
opg.FilterIndex = 1;
opg.RestoreDirectory = true;
if (opg.ShowDialog() == DialogResult.OK)
strUrl = "";
strUrl = opg.FileName;
if (strUrl != "")
{
Bitmap bmp = new Bitmap(opg.FileName);
pictureBox1.Image = Image.FromFile(strUrl);
}
}
private void txtRetrieve_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == false && Convert.ToInt32(e.KeyChar) != 8)
{

MessageBox.Show("Enter Numerics Only");
e.Handled = true;
}
}

1 comment:

  1. hi vamshi...the above code works better only for WF applications for web applications its not good i think....

    ReplyDelete