2016-12-02 38 views
0

我在数据类型image(二进制)的一列保存的图像到我的SQL Server数据库和它的成功保存。现在我需要在我的数据列表进行检索,但我得到这个错误:无法投类型“System.Int32”的对象键入“System.Byte []”在从SQL Server获取图像数据

无法转换类型“system.int32”的对象键入“system.Byte”

我可以理解任何一个检查我的代码,在那里我有错

private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      string sql = "SELECT Name,[Last Name],[Father Name],[Passport Number],Sh_ID ,I_ID,Email,[Phone Number], [Address], [Attorney In Iran], [Application Text] ,[Application Title Code] ,[Total Payment] ,[Total Paid],[Iran Case Status],[USA Case Status],Balance,[Customer picture] from permanentCustomer where (I_ID='"+textBoxIDN.Text+"' and [Last Name]='"+textBoxLN.Text+"') or (Sh_ID='"+textBoxBCN.Text+"' and [Last Name]='"+textBoxLN.Text+"') or Sh_ID='"+textBoxBCN.Text+"' or I_ID='"+textBoxIDN.Text+"' "; 
      if (conn.State != ConnectionState.Open) 
       conn.Open(); 
      // MessageBox.Show("1"); 
      command = new SqlCommand(sql, conn); 
      // MessageBox.Show("2"); 
      SqlDataReader reader = command.ExecuteReader(); 
      //MessageBox.Show("3"); 
      reader.Read(); 
      // MessageBox.Show("4"); 
      if (reader.HasRows) 
      { 
       textBoxFN.Text = reader[0].ToString(); 
       textBoxLN.Text = reader[1].ToString(); 
       textBoxFatherN.Text = reader[2].ToString(); 
       textBoxPN.Text = reader[3].ToString(); 
       textBoxBCN.Text = reader[4].ToString(); 
       textBoxIDN.Text = reader[5].ToString(); 
       textBoxEmail.Text = reader[6].ToString(); 
       textBoxPhoneN.Text = reader[7].ToString(); 
       textBoxAddress.Text = reader[8].ToString(); 
       textBoxAI.Text = reader[9].ToString(); 
       richTextBoxAT.Text = reader[10].ToString(); 

       textBoxTPayments.Text = reader[11].ToString(); 
       textBoxTPaid.Text = reader[12].ToString(); 
       textBoxICS.Text = reader[13].ToString(); 
       textBoxUCS.Text = reader[14].ToString(); 
       textBoxbalance.Text = reader[15].ToString(); 
       byte[] img = (byte[])(reader[16]); 
       if (img == null) { picCustomer.Image = null; } 
       else { MemoryStream ms = new MemoryStream(img); } 


      } 
      else { MessageBox.Show("This Record is not exist!"); } 
      conn.Close(); 
     } 
     catch(Exception ex) 
     { 
      conn.Close(); 
      MessageBox.Show(ex.Message); 
     } 
    } 
+0

我想你应该[设置可视工作室打破例外。(https://msdn.microsoft.com/en-us/library/d14azbfh(v = vs.110)的.aspx) – radarbob

+1

[SQL注入警报(http://msdn.microsoft。 com/en-us/library/ms161953%28v = sql.105%29.aspx) - 你应该不**将你的SQL语句连接在一起 - 使用**参数化查询**来避免SQL注入 –

+0

'image'数据类型为**弃用**,并且将在未来版本的SQL Server中删除。避免在新的开发工作中使用这种数据类型,并计划修改当前正在使用它们的应用程序。改用'varbinary(max)'。 [查看详情这里(http://msdn.microsoft.com/en-us/library/ms187993.aspx) –

回答

3

您收到此错误,因为该指数似乎并不正确:

byte[] img = (byte[])(reader[17]);  // instead of 16, if I counted correctly 

应该工作。然而,使用,而不是整数一个字符串索引强烈建议避免这种错误,并且还能够在你的查询添加/删除列,而不改变了很多指标:

var img = (byte[])(reader["Customer picture"]); 
+0

非常感谢帮助和您的意见 –

相关问题