如何从gridview中检索图像---- Convert.ToBase64String((byte [])Eval(“ImageData”))

时间:2015-11-16 22:01:59

标签: c# asp.net gridview

我尝试将图像检索到gridview,但出现此错误。

  

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

我的桌子是

图片--------------------------------------

ImageID int主键

ImageName nvarchar(300)

ImageData varbinary(Max)

PicDetail nvarchar(16)

AlbumID int

这是我的代码

<form id="form1" runat="server">
     <table class="auto-style1">
            <tr>
                <td class="auto-style2">Album</td>
                <td class="auto-style3">
                    <asp:DropDownList ID="ddlSubjects" runat="server" Height="16px" Width="370px">
                    </asp:DropDownList>
                </td>
                <td class="auto-style3">
                    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
                </td>
            </tr>

         <asp:GridView ID ="GridView1" runat ="Server" AutoGenerateColumns="False">
             <Columns>

                 <asp:BoundField DataField ="PicDetail" HeaderText ="PicDetail" />
                 <asp:BoundField DataField ="AlbumID" HeaderText ="AlbumID" />
                 <asp:TemplateField HeaderText ="Image">
                 <ItemTemplate>
                     <asp:Image ID ="Image1" runat="server" 
                        ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("ImageData")) %>'  Height="150px" Width="150px"/>
                </ItemTemplate>
                   </asp:TemplateField>      





             </Columns>
         </asp:GridView>
</table>

C#代码是

namespace WebApplication6
{
    public partial class WebForm21 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDropDownListData();

            }

        }
        private void BindDropDownListData()
        {
            string Albums = ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;




            try
            {
                using (SqlConnection sqlConn = new SqlConnection(Albums))
                {
                    using (SqlCommand sqlCmd = new SqlCommand())
                    {
                        sqlCmd.CommandText = "Select AlbumID,AlbumName from dbo.Albums";
                        sqlCmd.Connection = sqlConn;
                        sqlConn.Open();
                        SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        ddlSubjects.DataSource = dt;
                        ddlSubjects.DataValueField = "AlbumID";
                        ddlSubjects.DataTextField = "AlbumName";
                        ddlSubjects.DataBind();
                        sqlConn.Close();


                        ddlSubjects.Items.Insert(0, new ListItem("Please select", "0"));
                    }
                }
            }
            catch { }


        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;

            using (SqlConnection con = new SqlConnection(Artists))
            {


                int FkAlbum = Int32.Parse(ddlSubjects.SelectedValue);


                SqlCommand cmd = new SqlCommand("SELECT [PicDetail],[AlbumID],[ImageData] FROM [dbo].[Images] where[AlbumID] = @AlbumID", con);

                cmd.Parameters.AddWithValue("@AlbumID", FkAlbum);


                con.Open();

                GridView1.DataSource = cmd.ExecuteReader();

                GridView1.DataBind();
            }
        }
    }
}

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

> Exception Details: System.InvalidCastException: Unable to cast object
> of type 'System.DBNull' to type 'System.Byte[]'.
> 
> Source Error: 
> 
> 
> Line 24:                  <asp:TemplateField HeaderText ="Image"> Line
> 25:                  <ItemTemplate> Line 26:                     
> <asp:Image ID ="Image1" runat="server"  Line 27:                      
> ImageUrl='<%# "data:image/jpg;base64," +
> Convert.ToBase64String((byte[])Eval("ImageData")) %>'  Height="150px"
> Width="150px"/> Line 28:                 </ItemTemplate>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果您没有相册的图像文件,则数据将作为Eval(“ImageData”)中的System.DBNull值返回。 System.DBNull.Value的值不能转换为字节数组。

您可以通过在没有相册时为相册设置默认空白图片来解决此问题。

ImageUrl='<%# ((Eval("ImageData") is System.DBNull) ? "[Path to blank image]" : "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("ImageData"))) %>'