Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hi in my project am trying to save image into sqlserver and display it into grid..but while runtime am getting erorr in this code and record not saving to database?


//read image file
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;
        }
//display image in picture box when i select perticular cell
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["cdCustomerPhoto"].Value;
                Image newImage;
                using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);
                    newImage = Image.FromStream(ms, true);
                }

                pictureBox1.Image = newImage;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


//btnsave clikc

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] imageData = ReadFile(txtImagePath.Text);
                //string ID = textBox1.Text;
                string Name = tbName.Text;
                string Mobile = tbMobile.Text;
                string Age = tbAge.Text;
                string JoindDate = tbJoinDate.Text;
                string Sex = tbSex.Text;
                string DOB = tbDateOfBirth.Text;
                string IDProof = tbIDProof.Text;

                SqlConnection CN = new SqlConnection(@"Data Source=ythisbug;Initial Catalog=Exchange;Integrated Security=True;");
                string qry = "insert into tblCustomerDetails (cdCustomerName,cdCustomerSex,cdCustomerPhNo,cdCustomerDOB,cdCustomerJoinDate,cdCustomerAge,cdCustomerIDProofNo,cdCustomerPhoto) values(@Name,@Sex,@Mobile,@Dob,@Join,@Age,@Idproof,@ImageData)";

                SqlCommand SqlCom = new SqlCommand(qry, CN);
                //CN.Open();
               // SqlCom.Parameters.Add(new SqlParameter("@ID", (object)textBox1.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Name", (object)tbName.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Sex", (object)tbSex.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Mobile", (object)tbMobile.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Dob", (object)tbDateOfBirth.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Join", (object)tbJoinDate.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Age", (object)tbAge.Text));
                SqlCom.Parameters.Add(new SqlParameter("@Idproof", (object)tbIDProof.Text));
                SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
                CN.Open();
                SqlCom.ExecuteNonQuery();
                CN.Close();

                GetImagesFromDatabase();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
               

        }




//this errorr in btn click save
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at Exchange.CustomerRegistration.button1_Click(Object sender, EventArgs e) in C:\Users\ythisbug\Documents\Visual Studio 2008\Projects\ShiroorExchangeWindowsApp\Exchange\CustomerRegistration.cs:line 75



//

here is my code
C#
void GetImagesFromDatabase()
      {
          try
          {
              SqlConnection CN = new SqlConnection(@"Data Source=ythisBut;Initial Catalog=Exchange;Integrated Security=True;");
              SqlDataAdapter ADAP = new SqlDataAdapter("Select * from tblCustomerDetails", CN);
              DataSet DS = new DataSet();
              ADAP.Fill(DS, "tblCustomerDetails");//this line error
              dataGridView1.DataSource = DS.Tables["tblCustomerDetails"];
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.ToString());
          }
      }

error:
System invalid operation exception instance failure

at System.data.Common.dbdataadapter.fill(dataset dataset,string src table)
at Exchange.customerregistration.getImagesFromDatabase() in c:\Users\ythisbug\documents\visual studio 2008\projects\exchange\exchange\CustomerRegistration.cs:line 95

can any one help me to solve this..
thanks in advance
Posted
Updated 21-Jul-12 23:10pm
v4
Comments
Sandeep Mewara 22-Jul-12 5:07am    
It looks all good to me right now. Is there anything else to the error? event viewer logs? Debug?
ythisbug 22-Jul-12 5:09am    
no while running project am egging this imagefromdatabase error instance failure and while saving instance failure
[no name] 22-Jul-12 6:59am    
SqlConnection CN = new SqlConnection(@"Data Source=ythisBut <-----
ythisbug 22-Jul-12 7:01am    
aday that spelling mistake.its ythisbug

Just use the following :
C#
ADAP.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
 
Share this answer
 
Comments
Sandeep Mewara 22-Jul-12 4:38am    
I doubt if this would solve the issue. I don't see any issue with giving a table name in the dataset.
Mehdi Gholam 22-Jul-12 4:45am    
I believe the fill will look for the table name to fill in the dataset and since it does not exist you will get an error.
Sandeep Mewara 22-Jul-12 5:01am    
Nopes. Fill method will fill data into a table giving it the name as mentioned in Fill method.

It will not look for any table.
Here:
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx
http://msdn.microsoft.com/en-us/library/y4b211hz%28v=vs.80%29.aspx
ythisbug 22-Jul-12 4:58am    
error is the samne.am retrieving table data in gridview so i set table name
Ok, based on the new errors added, it looks like there is some connectivity issue. Make sure your connection string is correct and you are able to connect to DB.

Your issue is with connection to DB. Adapter internally deals with connection during Fill so both the issues point to one connectivity issue only.


UPDATE:

i tried more than three sample project for saving image in database..bt its not working.or just give me link simple and easy
Storing and Retrieving Images from SQL Server Using Strored Procedures and C#.net[^]
C# Photo Album Viewer[^]
Store or save images in SQL Server database using C# [^]
Inserting and Retrieving images from SQL Server Database using C#[^]
 
Share this answer
 
v2
Comments
ythisbug 22-Jul-12 5:12am    
thanks sandeep..but in other forms save and retrieving data to datagrid working fine..for this form only error..
Sandeep Mewara 22-Jul-12 7:07am    
You sure that the connection string at other forms are same?
ythisbug 22-Jul-12 7:08am    
ya same .
ythisbug 22-Jul-12 7:09am    
and again i tried another example
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/

for this am getting error same as above..Instance failure
Sandeep Mewara 22-Jul-12 7:20am    
Well, it's difficult to say based on what you are able to share right now.

Try a sample project and see if the same code works there or not

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