【问题标题】:Retrieving images from the database and injecting them into listview从数据库中检索图像并将它们注入列表视图
【发布时间】:2013-01-24 22:59:57
【问题描述】:

我有一个表 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();
}

有什么建议吗?

【问题讨论】:

  • 看看这个articlethis..它会用一个例子来准确解释

标签: c# asp.net database image listview


【解决方案1】:

图像可以通过使用通用处理程序显示到列表视图或任何其他控件中。 通过添加新项目 > 通用处理程序来添加通用处理程序,然后参考下面的代码

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

【讨论】:

  • +1,我刚刚从中学到了两件事:如何使用处理程序以及如何从数据库中检索图像并使用它。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多