日期:2014-05-17  浏览次数:20472 次

image控件的使用
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace 数据访问
{
    public partial class ShowPhoto : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Repeater.DataSource = getphoto();
                Repeater.DataBind();
                
            }


        }

        public List<string> getphoto()
        {
            List<string> photos = new List<string>();
            string photoPath = MapPath("~/photos");
            string[] files = Directory.GetFiles(photoPath);
            foreach (string photo in files)
            {
                photos.Add("/photos" + Path.GetFileName(photo));
            }
            return photos;
        }
    }
}

HTML code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowPhoto.aspx.cs" Inherits="数据访问.ShowPhoto" %>

<!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>Show Photos</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Repeater ID="Repeater" runat="server">
    <ItemTemplate>
    <asp:Image ID="image" Width="500px" ImageUrl='<%#container.dataitem %>' runat="server">
    </ItemTemplate>
    </asp:Repeater>
    
    </div>
    </form>
</body>
</html>


上面这个代码是书上的,可是上面的一个数据绑定在后台没有声明啊
我想将一个文件夹的图片全部显示出来 应该如何写代码?

------解决方案--------------------
<%# %>里是大小写敏感的

改成Container.DataItem试一试
------解决方案--------------------
代码里还有不少问题。
1. 缺少</asp:Image>
2. 图片相对路径错了

下面是我改正后的代码,测试过了,可以的

C# code

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Repeater.DataSource = getphoto();
                Repeater.DataBind();

            }
        }

        public List<string> getphoto()
        {
            List<string> photos = new List<string>();
            string photoPath = MapPath("~/photos");
            string[] files = Directory.GetFiles(photoPath);
            foreach (string photo in files)
            {
                photos.Add("photos/" + Path.GetFileName(photo));
            }
            return photos;
        }

------解决方案--------------------
<asp:Image ID="image" Width="500px" ImageUrl='<%#container.dataitem %>' runat="server">
就是这里的问题。image没结束 写成
<asp:Image ID="image" Width="500px" ImageUrl='<%#container.dataitem %>' runat="server" />这样既可

Container是Repeater 的一行,而Container.DataItem是这一行所绑定的数据。

参考http://www.cnblogs.com/zjwei55/archive/2011/08/31/2161415.html