2013-05-27 64 views
0

我有以下代碼以在datalist中顯示圖像。datalist的動態模板字段

 if (!IsPostBack) 
    { 
     string str="~/"+txt1.Text+"/"; 
     DirectoryInfo dir = new DirectoryInfo(MapPath("str")); 
     FileInfo[] files = dir.GetFiles(); 
     ArrayList list = new ArrayList(); 
     foreach (FileInfo oItem in files) 
     { 
      if (oItem.Extension == ".jpg" || oItem.Extension == ".jpeg" || oItem.Extension == ".gif") 
       list.Add(oItem); 
      //Image ImageData= (Image)DataList1.FindControl("Image1"); 
      //ImageData.ImageUrl = dir.ToString()+"{0}"; 
     } 
     DataList1.DataSource = list; 
     DataList1.DataBind(); 

    } 

在ASPX:

<asp:DataList ID="DataList1" runat="server" RepeatColumns="10" CellPadding="5"> 
<ItemTemplate> 
<asp:Image Width="20" Height="20" ID="Image1" ImageUrl='<%# Bind("Name", "~/ajax _main/testpages/images/{0}") %>' runat="server" /> 
<br /> 
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/ajax _main/testpages/images/{0}") %>' runat="server"/> 
</ItemTemplate> 
<ItemStyle BorderColor="silver" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center" 
VerticalAlign="Bottom" /> 
</asp:DataList> 

我要定義CS文件這個模板,這樣我就可以根據txt1.Text改變導航網址。任何人都可以幫我做這件事嗎?

回答

1

嘗試

DirectoryInfo dir = new DirectoryInfo(MapPath(str)); 

注意,我刪除""從STR

當你結合你可以綁定像下面

var paths = dir.GetFiles() 
    .Where(f => f.Extension == ".jpg" || f.Extension == ".jpeg" || f.Extension == ".gif") 
    .Select(p => new { Name = MapPathReverse(p.FullName) }) 
    .ToList(); 
DataList1.DataSource = paths; 
DataList1.DataBind(); 

從物理路徑得到的相對路徑路徑我用下面的方法

public static string MapPathReverse(string fullServerPath) 
{ 
    return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty); 
} 

現在你可以改變的aspx我這個errorSystem.Web.HttpException結合

ImageUrl='<%# Bind("Name") %>' 
+0

得到:數據綁定:「System.String」不包含名爲「名稱」的屬性。 – Shanna

+0

請檢查更新後的答案 – Damith

+0

非常感謝。有效。我非常需要這個。再次感謝 – Shanna