无法转换类型为#System; Int32'的对象输入' System.Byte []'从SQL Server获取图像数据

时间:2016-12-02 22:14:52

标签: c# sql-server

我在一个数据类型为image(二进制)的列中将图像保存到我的SQL Server数据库中,并且已成功保存。现在我需要在我的datalist中检索它,但是我收到了这个错误:

  

无法转换' 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);
        }
    }

1 个答案:

答案 0 :(得分:3)

您收到此错误,因为索引似乎不正确:

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

应该有效。但是,强烈建议使用字符串索引器而不是整数1来避免此类错误,并且还可以在不更改大量索引的情况下在查询中添加/删除列:

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