Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
i am inserting an image in sql server and fatch this image to another web form.
but is show and error my code is
this code is use for insert image into sqldatabase column imgdata is varchar type:
C#
OpenFileDialog dlg = new OpenFileDialog();
            DialogResult dlgRes = dlg.ShowDialog();
            if (dlgRes != DialogResult.Cancel)
            {
                //Set image in picture box
                pictureBox1.ImageLocation = dlg.FileName;
                //Provide file path in txtImagePath text box.
                txtimagepath.Text = dlg.FileName;
            }
  MemoryStream stream = new MemoryStream();
                pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] imageData = stream.ToArray();    

//and below code use for fatch image :
 SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select imgdata from Joiningform where regno='" + regno + "'",con));
           DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            if (dataSet.Tables[0].Rows.Count == 1)
            {
                Byte[] data = new Byte[0];
                data = (Byte[])(dataSet.Tables[0].Rows[0]["imgdata"]);
                MemoryStream mem = new MemoryStream(data);
                pictureBox1.Image = Image.FromStream(mem);
                
            }  

but below exception is display on that line: DataSet dataSet = new DataSet(); System.InvalidOperationException was unhandled
Message=Fill: SelectCommand.Connection property has not been initialized.
Posted
Updated 18-Oct-15 18:30pm
v3

You're code just looks good.
But still, try to Open the connection before using it for SqlAdapter.
C#
con.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select imgdata from Joiningform where regno='" + regno + "'",con));


-KR
 
Share this answer
 
Comments
Member 10273293 19-Oct-15 2:01am    
now the Exception is:
Unable to cast object of type 'System.String' to type 'System.Byte[]'.
my table datatype is string ,should i change it in image ? because sql 2005 don't have byte datatype.
It seems you doesn't initilise SQL connection and connection string,
First create SQL connection with connection string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900