对DataList控件绑定图片的一点小结

      最近一直很关注NBA的季后赛,虽然我最喜欢的火箭队没有杀入西部决赛行列,但我想这已经足够了,呵呵,为此,我特意收集了一下NBA一些球员的信息,并且简单的做了一个数据库,算是自娱自乐吧,然后跟自己正在学的Asp.net做点铺垫,毕竟数据源控件没数据哪能行啊,于是凑合这个数据库用了下。

      以前用DataList的时候没有去绑定图片,听人说很简单,但自己没试过,结果也花了点功夫去研究怎么样绑定到图片,毕竟Eval()函数绑定的数据是非byte[]型的。下面我可能说的大多数朋友都会了,可以直接飘过就行了,呵呵,我说的只是自己对所学的知识的一点总结,希望也能帮到正在初学Asp.Net朋友的一些忙。

       

这是我建立的数据库,入库的时候自己特意写了一个应用程序来专门添加图片,因为列Logo,photo都是Imgae类型的,手动添加很方便入库。

下面就是我的Datalist.aspx页面的内容,由于在做练习的时候做了个模板,因为我做的时候也写了其他数据源控件的页面,所以这个位置就只贴页面代码,模板页面代码就省了:

 

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="DataList.aspx.cs" Inherits="DataList" Title="DataList控件" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="height: 102%; 758px">
        <asp:DataList ID="dlPlayerDetails" runat="server" Width="650px"
            GridLines="Horizontal" Height="1051px">
            <SeparatorTemplate>
                <hr  style="color:Red" />
            </SeparatorTemplate>
            <HeaderTemplate>
                <center style="font-size:large; color:Blue">NBA球员详细信息</center>
            </HeaderTemplate>
            <FooterTemplate>
                <h5 style="text-align:right; color:Red">制作人:Microered</h5>
            </FooterTemplate>
        <ItemTemplate>
        <table width="100%" >
        <tr  style="height:100%">
                 <td  style="25%">
                     <img alt="球员照片" src="<%# "ShowPlayerImage.aspx?PlayerID="+Eval("PlayerID")%>"  width="100%" height="100%"/>
                </td>
            <td style="75%">
                <table width="100%">
                    <tr>
                        <td><span>姓名:</span></td>
                        <td><span><%# Eval("NameCH") %></span></td>
                        <td><span>所属球队:</span></td>
                        <td><span><%# Eval("TeamNameCH") %></span></td>
                    </tr>
                    <tr>
                        <td><span>位置:</span></td>
                        <td><span><%# Eval("Position") %></span></td>
                        <td><span>球员号码</span></td>
                        <td><span><%# Eval("Number") %></span></td>
                    </tr>
                    <tr>
                        <td><span>身高:</span></td>
                        <td><span><%# Eval("Height") %></span></td>
                        <td><span>体重:</span></td>
                        <td><span><%# Eval("Weight") %></span></td>
                    </tr>
                    <tr>
                        <td><span>生日:</span></td>
                        <td><span><%# Eval("Birth") %></span></td>
                        <td><span>球龄:</span></td>
                        <td><span><%# Eval("LengthService") %></span></td>
                    </tr>
                </table>
            </td>
        </tr>
        </table>
        </ItemTemplate>
        </asp:DataList>
</div>
</asp:Content>
1.在做绑定的时候我也特意写了一个SqlHelper类来更好的完成数据的访问,这样也大量减少了代码的书写量,提供的代码如下:

注:用的IDE是VS2008

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DBHelper
{
    public class DALHelper
    {
        private static string constr = ConfigurationManager.ConnectionStrings["MyNBAData"].ConnectionString;
        private static SqlConnection connection = new SqlConnection(constr);
   
        /// <summary>
        /// 检查连接是否打开
        /// </summary>
        public static void CheckConnOpen()
        {
            if (connection == null || connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
        }
        /// <summary>
        /// 检查连接是否关闭
        /// </summary>
        public static void CheckConnClosed()
        {
            if (connection!=null||connection.State==ConnectionState.Open)
            {
                connection.Close();
            }
        }

        /// <summary>
        /// 获取一个DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql)
        {
            SqlDataAdapter da = null;
            DataTable dt = null;
            try
            {
                da = new SqlDataAdapter(sql, connection);
                dt = new DataTable();
                da.Fill(dt);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
          
            return dt;
        }

     /// <summary>
     /// 获取DataReader对象
     /// </summary>
     /// <param name="sql"></param>
     /// <param name="parms"></param>
     /// <returns></returns>
        public static SqlDataReader ExecuteReader(string sql, SqlParameter[] parms)
        {
            SqlCommand command= null;
            SqlDataReader reader = null;
            try
            {
                command = new SqlCommand(sql, connection);
                if (parms!=null)
                {
                    foreach (var item in parms)
                    {
                        command.Parameters.Add(item);
                    }
                }
                CheckConnOpen();
                reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
            finally
            {
                //CheckConnClosed();
            }
            return reader;
        }
    
        /// <summary>
        /// 执行数据库的修改,插入,删除
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string sql, SqlParameter[] parms)
        {
            SqlCommand command = null;
            int count = 0;
            try
            {
                command = new SqlCommand(sql, connection);
                if (parms!=null)
                {
                    foreach (var item in parms)
                    {
                        command.Parameters.Add(item);
                    }
                }
              
                CheckConnOpen();
                count = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

                throw new Exception(ex.ToString());
            }
            finally
            {
                CheckConnClosed();
            }
            return count;
        }
    }
}
2.下面就是DataList.aspx的后台代码:

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class DataList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataList();
        }
    }
    /// <summary>
    /// 绑定数据到DataList
    /// </summary>
    public void BindDataList()
    {
        string sql = "SELECT   Player.*, Team.TeamNameCH  "+
                           "FROM    Player INNER JOIN  "+
                           " Team ON Player.TeamID = Team.TeamID";
        DataTable dt = DBHelper.DALHelper.GetDataTable(sql);
        dlPlayerDetails.DataSource = dt;
       
        dlPlayerDetails.DataBind();
       
    }
}
3.细心的朋友可能会发现在页面代码的时候绑定的球员相片是这样的:

    <img alt="球员照片" src="<%# "ShowPlayerImage.aspx?PlayerID="+Eval("PlayerID")%>"  width="100%" height="100%"/>
那是因为我们要把显示的球员相片通过单独建立的另外一个页面ShowPlayerImage.aspx来显示具体的图片,这也是图片绑定解决方法之一,可能性能上会有所影响,但这里只谈实现。

4.下面所要讲的就是ShowPlayerImage.aspx页面内容:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowPlayerImage.aspx.cs" Inherits="ShowPlayerImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>照片显示</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>
大家会看到这个页面基本上没多少内容,因为这个页面只是绑定图片的一个过渡页面。

 5.当然,ShowPlayerImage.aspx的后台代码才是我们最关心的,因为页面本身的功能是显示相片的:

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
public partial class ShowPlayerImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int playerID = Convert.ToInt32(Request.QueryString["PlayerID"]);
            byte[] bytes = BindImage(playerID);

            Response.Clear();
            if (bytes != null)
            {
                Response.BinaryWrite(bytes);
            }
            else
            {
                Response.BinaryWrite(LoadUnknowImage());
            }
            Response.End();
        }
    }
   
    /// <summary>
    /// 绑定数据库中的球员相片
    /// </summary>
    /// <param name="playerID">该参数是用来接收DataList.aspx页面传过来的球员ID</param>
    /// <returns></returns>
    public byte[] BindImage(int playerID)
    {
        string sql = "select Photo from Player where
PlayerID=@PlayerID";
        SqlDataReader reader = null;
        byte[] photoBytes=null;
        try
        {
            SqlParameter parm = new SqlParameter("@PlayerID", SqlDbType.Int);
            parm.Value = playerID;
            reader = DBHelper.DALHelper.ExecuteReader(sql, new SqlParameter[] {parm});
            while (reader.Read())
            {
                if (!(reader["Photo"] is DBNull))
                {
                    photoBytes = (byte[])reader.GetSqlBinary(0);
                }
            }

        }
        finally
        {
           
            reader.Close();
        }
        return photoBytes;
    }

    /// <summary>
    /// 当未能从数据中取得相片时我们用一张事先准备好的图片来替代,该图片在网站的App_Themes的文件夹下
    /// </summary>
    /// <returns></returns>
    public byte[] LoadUnknowImage()
    {
        byte[] bytes = null;
        FileStream fs = null;
        BinaryReader readBytes = null;
        try
        {
            fs = new FileStream(Server.MapPath("~/App_Themes/Pictures/unknow.jpg"), FileMode.Open, FileAccess.Read);
            readBytes = new BinaryReader(fs);
            bytes = readBytes.ReadBytes(Convert.ToInt32(fs.Length));
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }
        finally
        {
            readBytes.Close();
            fs.Close();
        }
        return bytes;
    }
}

 这样所有代码就可以实现图片绑定了,运行结果如下:

原文地址:https://www.cnblogs.com/ecin/p/1486730.html