insert image into database by using winforms

Posted by Kishore under C# on 5/27/2010 | Views : 7676 | Status : [Member] | Replies : 1
hi,

i created a form that contains two buttons like (browse and save) and one picturebox control, when i click the browse button a open dialog box will be opened and the selected image displayed in picture box then i click the save button the image will be stored in database. i tried this with the following code but it displays some error like "FAILED TO CONVERT PARAMETER VALUE FROM A STRING TO INT32".....


and my code is...

private void btnbrowse_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = @"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures";
openFileDialog1.Filter = "all files|*.*|word docs|*.doc|text files|*.txt|image files|*.jpg;*.mpeg;*.png";
openFileDialog1.ShowDialog();
string fname=openFileDialog1.FileName;
pictureBox1.ImageLocation = fname;

}


private void btnsave_Click(object sender, EventArgs e)
{
FileStream fs;
byte[] btnarray;
try
{
fs = new FileStream(fname, FileMode.Open);
btnarray = new byte[fs.Length];
fs.Read(btnarray, 0, Convert.ToInt32(fs.Length));
cmd = new SqlCommand("insrtimg", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@spuserid", SqlDbType.Int);
p1.Value = textBox1.Text;
cmd.Parameters.Add(p1);
p1 = new SqlParameter("@spuserphoto", SqlDbType.Image);
p1.Value = btnarray;
cmd.Parameters.Add(p1);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record is inserted");
}
catch (Exception exe)
{
MessageBox.Show(exe.Message);
}

}

please solve my problem....




Responses

Posted by: Er.deepakdalal on: 5/27/2010 [Member] Starter

Up
0
Down
Hi Kishore

Try this code for inserting your image directly from its path into the database

byte[] img = File.ReadAllBytes("your image path");
cmd.commandtext = "INSERT INTO MyTable(Image) VALUES(@Image)";
cmd.Parameters.AddWithValue("@Image", img);
cmd.ExecuteNonQuery();

Where

cmd:- is a Sql Command
@Image:- is a parameter

Kishore, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response