Retrieve all images from a folder and display them using a DataList control


With the use of the following code you can retrieve all images from any folder and display them in a form using a DataList control of ASP.Net.

To retrieve images from a folder this article provides a few steps which will be easy to follow.

Step 1:

Design a Form; drag a DataList Control from the toolbox onto the form. Set the Repeated Column property and design the DataList control as you need. I am using an image button and a link button in my form.

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" BackColor="White"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"   ForeColor="Black"
             Width="100%">
           <FooterStyle BackColor="#CCCCCC" />
                       <SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                        <HeaderTemplate>
                                   <span class="style2">Image Gallary</span>
            </HeaderTemplate>
                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                      <ItemTemplate>
                      <asp:ImageButton Width="105px" ID="Image1" runat="server"  BorderStyle="Solid" ImageUrl='<%# Bind("Name", "~/[foldername]/{0}") %>'
                      Height="94px"  />
                          <br />
                          <asp:LinkButton ID="HyperLink1" Text='<%# Bind("Name") %>'  CommandArgument='<%# Bind("Name") %>'  runat="server" />
                      </ItemTemplate>
                          <FooterStyle BackColor="White" ForeColor="#333333" />
                          <ItemStyle BorderColor="Silver" BorderStyle="Dotted" BorderWidth="1px" HorizontalAlign="Center"
                              VerticalAlign="Bottom" BackColor="White" ForeColor="#333333" />
</asp:DataList>

Step 2:

Write the function below and call it in the Form Load event. 

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" || file2.Extension == ".png")
        {
            list.Add(file2);
        }
    }
    DataList1.DataSource = list;
    DataList1.DataBind();
}

Step 3: Run your website........ 


Similar Articles