将二进制图像从数据库显示到gridview中。

时间:2018-09-25 09:06:10

标签: c# sql-server image binary-data

我正在尝试从数据库检索二进制图像并将其显示在GridView控件中。可以在GridView中显示SQL Server中名为[student]的表,但[Image]列除外。这是我的C#代码,试图从数据库中检索二进制图像:

protected void Page_Load(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["SAOSConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM student", conn))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView dr = (DataRowView)e.Row.DataItem;
            string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["Image"]);
            (e.Row.FindControl("Image1") as Image).ImageUrl = imageUrl;
        }
    }

从上面的代码中,我从下面这一行收到错误:它表示无法将类型为“ System.DBNull”的对象转换为类型为“ System.Byte []”。

string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["Image"]);

2 个答案:

答案 0 :(得分:0)

正如InvalidCastException消息所言,在转换为字节数组之前,必须对if进行DBNull.Value条件检查:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dr = (DataRowView)e.Row.DataItem;

        if (dr["Image"] != DBNull.Value)
        {
            var imageControl = e.Row.FindControl("Image1") as Image;

            var encodedImage = Convert.ToBase64String((byte[])dr["Image"]);
            string imageUrl = "data:image/jpg;base64," + encodedImage;
            imageControl.ImageUrl = imageUrl;
        }
    }
}

或者,您可以使用Convert.IsDBNull(dr["Image"])检查,如果dr["Image"]包含DBNull.Value,则返回true。

答案 1 :(得分:0)

我使用了telerik radGrid。请看一看。希望您能找到解决方案

网格列

<telerik:GridBinaryImageColumn DataField="ImageData" ResizeMode="Fit" 
   ImageHeight="100px"
   HeaderText="Image" AlternateText="No Image" ImageWidth="100px" 
   UniqueName="ImageData">
  <HeaderStyle HorizontalAlign="Left" Width="10%" />
  <ItemStyle HorizontalAlign="Left" Font-Size="15px" />
</telerik:GridBinaryImageColumn>

C#代码

if (req["ImageData"] != DBNull.Value)
{
   byte[] imageData = (byte[])req["ImageData"];
   string base64String = Convert.ToBase64String(imageData, 0, imageData.Length);
   dtRow["ImageData"] = base64String;
   _item.ImageData = imageData;
   _items.Add(_item);
}