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

本文关键字:显示 显示图 图像 Datagrid 中的 sqldatareader 使用 | 更新日期: 2023-09-27 18:37:23

我从数据网格在图片框中显示图像时遇到问题。 我使用了SQL连接并使用SQLdataReader获取数据。我在sql服务器中以系统字节格式保存了图片,但是当我单击数据网格中的行时无法显示图片

请协助我

将值从读取器加载到数据网格

 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; }
    }
}

数据网格单击事件

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;

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

这一行有问题:

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

您需要从数据库中获取以字节为单位的图像,请参阅此处 使用 SqlDataReader 获取二进制数据