从数据库中检索图像并将它们注入到listview中
本文关键字:注入 listview 数据库 检索 图像 | 更新日期: 2023-09-27 17:58:31
我有一个表BIKETYPE{BIKETYPEID,NAME,DESCRIPTION,IMAGE}。
IMAGE的数据类型为image
。我正试图通过列表视图显示该表。我可以看到除图像栏之外的所有内容。
我的代码如下
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem,"BikeTypeId") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Name") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Description") %></td>
<td><asp:Image ImageUrl='<%# "Handler.ashx?BikeTypeId="+ Eval("image") %>' ID="Image" runat="server" /></td>
<td><asp:Button ID="Select" runat="server" Text="Select" CommandName="Select" /></td>
</tr>
</ItemTemplate>
在后面的代码中,我使用了如下所示的简单绑定方法
protected void bind()
{
adp = new SqlDataAdapter("Select * From BikeType", str);
ds = new DataSet();
adp.Fill(ds);
ListView1.DataSource = ds;
ListView1.DataBind();
ds.Clear();
adp.Dispose();
}
有什么建议吗?
可以使用Genric Handler将图像显示到listview或任何其他控件中。通过添加新项目>Genric Handlers添加Genric Handler,然后参考下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace letsride
{
/// <summary>
/// Summary description for Handler1
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["b_id"]);
string constr = ConfigurationManager.ConnectionStrings["bikewebConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select image from Biketype where BikeTypeId=@id";
cmd.Parameters.AddWithValue("id", id);
object img = cmd.ExecuteScalar();
try
{
context.Response.BinaryWrite((byte[])img);
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
在您的Web表单中使用图像作为
<asp:Image ID="i" runat="server" ImageUrl='<%# "Handler.ashx?b_id=" + Eval("BikeTypeId") %> ' /></td>
BikeTypeID是数据库中表的ID也可参考http://makhaai.blogspot.com.au/2010/11/image-handling-in-aspnet-part-1.html