Bind Images from Folder to Datalist

Posted by Venkat | Labels: ,

Here we are going to see how to bind the images from the folder to Datalist. I am storing the images on Server Folder , so i have to show what are the images available on the Folder it may be .png,.jpg or any ...

ASPX

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" CellPadding="5">
            <ItemTemplate>
            <asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server" />
                <br />
                <asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/images/{0}") %>' runat="server"/>
            </ItemTemplate>
                <ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
                    VerticalAlign="Bottom" />
</asp:DataList> 

see here, we get the files from the folder using System.IO Namesapce  , then i am checking the images on the folder ie: checking the extension that i am going to allow - to show it on Datalist. you can include the Extension whatever you want so that is going to add it on arrayList, then pass the array list to DataSource of the Datalist.


Code-Behind

protected void Page_Load(object sender, EventArgs e)
    {
        ListImages();
    }

    private void ListImages()
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("~/images"));
        FileInfo[] file = dir.GetFiles();
        ArrayList list = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".jpg" || file2.Extension == ".jpeg" || file2.Extension == ".gif")
            {
                list.Add(file2);
            }
        }
        DataList1.DataSource = list;
        DataList1.DataBind();
    }

PayOffers.in