我想在 asp:GridView 中显示“图像”列。这个想法是提供图像的缩略图,并链接到真实大小的图像。对于某些行,这可能是 PDF 文档。我希望链接到 PDF。PDF 或图像存储在 SQL 数据库中。
现在我在处理程序(.ashx)文件中有错误:
“不存在数据时尝试读取无效。”
这是我的代码:
ASP:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="assessment_id" HeaderText="assessment_id"
InsertVisible="False" ReadOnly="True"
SortExpression="assessment_id" />
<asp:BoundField DataField="a_mime" HeaderText="a_mime" SortExpression="a_mime" />
<asp:TemplateField HeaderText="a_data">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [assessment_id], [a_data], [a_mime] FROM [Assessments]">
</asp:SqlDataSource>
处理程序 ASHX:
<%@ WebHandler Language="C#" Class="Handler" %>
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select a_data from Assessments where assessment_id =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ImageID.Value = Convert.ToInt32(context.Request.QueryString["assessment_id"]);
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["a_data"]);
dReader.Close();
con.Close();
}
如果可能,请帮助我。如果耗时,请提供示例或博客文章的链接。