从目录中列出视图中的数据

时间:2013-11-08 15:07:31

标签: asp.net vb.net listview bind vb.net-2010

我有一个列表视图:

 <asp:ListView ID="ListView1" runat="server">
           <ItemTemplate>
                 <asp:ImageButton ID="ImageButton1" runat="server" />
           </ItemTemplate>
 </asp:ListView> 

我有vb中的图像链接:

  Dim dirInfo As string="D:\rbi\images\emoticons\"
  Dim filenames As List(Of String) = dirInfo.GetFiles().[Select](Function(j) j.Name).ToList()

我从目录中获取的链接和文件名不是来自数据库...所以如何在列表视图中绑定这些链接以显示所有图像?

2 个答案:

答案 0 :(得分:0)

将图像路径绑定到ListView的一种方法是让一个包含Public属性的对象在Eval()绑定中使用,如下所示:

代码隐藏:

Public Class ImageBinder
    Public Property path() As String
        Get
            Return m_path
        End Get
        Set
            m_path = Value
        End Set
End Property
Private m_path As String
End Class

您需要拥有现在将创建ImageBinder个对象列表的代码,而不仅仅是字符串列表。

现在,在您的标记中,您可以在path标记中引用ListView属性,如下所示:

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>
        <asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("path") %>' />
    </ItemTemplate>
</asp:ListView> 

注意:这将处理绑定,但您必须处理的问题是,如果您在问题中提供的示例路径(D:\rbi\images\emoticons\)是正确的,那么它将无法正常工作在ASP.NET的范围内,因为安全性约束不是应用程序的虚拟目录之外的路径。您需要创建一个虚拟目录,并将其用于您希望在ListView中显示的图像的路径。

答案 1 :(得分:0)

请尝试以下完整解决方案:

在aspx页面中:

   <asp:ListView ID="ListView1" runat="server">
       <ItemTemplate>
             <asp:ImageButton ID="ImageButton1" runat="server" ToolTip='<%#Eval("Name")%>'/>
       </ItemTemplate>
   </asp:ListView>

在aspx.vb页面中:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim di As New IO.DirectoryInfo(Server.MapPath("Images/emoticons/"))
        Dim diar1 As IO.FileInfo() = di.GetFiles()
        Dim dra As IO.FileInfo

        Dim FileList As New List(Of IO.FileInfo)
        'list the names of all files in the specified directory
        For Each dra In diar1
            FileList.Add(dra)
        Next

        ListView1.DataSource = FileList
        ListView1.DataBind()
    End Sub

    Protected Sub ListView1_ItemDataBound(sender As Object, e As  System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
        Dim ImageButton1 As ImageButton
        If e.Item.ItemType = ListViewItemType.DataItem Then
            Dim rowView As IO.FileInfo = e.Item.DataItem()
            Dim FileName As String = rowView.Name.ToString()
            ImageButton1 = e.Item.FindControl("ImageButton1")
            ImageButton1.ImageUrl = "~/Images/emoticons/" & FileName
        End If
    End Sub