使用sqldatareader在c#中使用Datagrid在pictureBox中显示图像

时间:2012-06-15 10:28:42

标签: c#

我有问题从Datagrid在pictureBox中显示图像。我使用sqlconnection并使用sqldatareader获取数据。我在sql server中以systembyte格式保存了图片但是当我点击datagrid中的行时我无法显示图片

请帮助我

将值从读取器加载到DATAGRID

 oCon.Open();
 SqlCommand get_company_histroy = new SqlCommand("sp_select_company_history", oCon);
 get_company_histroy.CommandType = CommandType.StoredProcedure;
 get_company_histroy.Parameters.Add("@Company_Code ",txtdetailcompcode.Text);

 oDr = get_company_histroy.ExecuteReader();

 ArrayList sequence = new ArrayList();
 while (oDr.Read())
 {
     Get_Histroy His = new Get_Histroy();
     His.Photo = oDr[6].ToString();
     sequence.Add(His);

     //txtcompdetailhisfounder.Text = Convert.ToString(oDr["History_Founder"]);
     //DTP_comp_details_his_since.Text=Convert.ToString (oDr["History_Since"]);
 }
 DG_Mas_Com_History.DataSource = sequence;

从读者那里获得价值的类别

public class Get_Histroy
{
    public  string Photo
    {
        get { return History_Photo; }
        set { History_Photo=value; }
    }
}

DATAGRID CLICK EVENT

private void DG_Mas_Com_History_CellClick(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        if (e.RowIndex >= 0)
            get_company_histroy.Parameters.Add("@Company_Code ", txtdetailcompcode.Text);
        oDr = get_company_histroy.ExecuteReader();

        byte[] picarr = (byte[])DG_Mas_Com_History.Rows[e.RowIndex].Cells[4].Value;
        ms = new MemoryStream(picarr);
        ms.Seek(0, SeekOrigin.Begin);
        PBcompdetailhisphoto.Image = System.Drawing.Image.FromStream(ms);
    }

我收到错误:

  

无法将'System.String'类型的对象强制转换为'System.Byte []'。)

来自

byte[] picarr = (byte[])DG_Mas_Com_History.Rows[e.RowIndex].Cells[4].Value;

1 个答案:

答案 0 :(得分:0)

这一行存在问题:

His.Photo = oDr[6].ToString();

您需要以字节为单位从数据库中获取图像,请参阅此处Getting binary data using SqlDataReader