Wednesday, 30 September 2015

Bind images in DataList from folder in ASP.Net using C#

HTML Markup

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:DataList ID="DataList1" runat="server" RepeatColumns = "2" CellPadding = "4">
    <ItemTemplate>
        <table border="0" cellpadding="0" cellspacing="0" width = "120px">
            <tr>
                <td align = "center">
                    <asp:Image ID="Image1" ImageUrl='<%# Eval("Value") %>' runat="server" Height="100"
                        Width="100" />
                </td>
            </tr>
            <tr>
                <td align = "center">
                    <%# Eval("Text"%>
                </td>
            </tr>
        </table>
    </ItemTemplate>

</asp:DataList>

Namespaces

using System.IO;
using System.Collections.Generic;

C#

protected void Upload(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}

Displaying images from folder on disk in ASP.Net DataList control

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            string fileName = Path.GetFileName(filePath);
            files.Add(new ListItem(fileName, "~/Images/" + fileName));
        }
        DataList1.DataSource = files;
        DataList1.DataBind();
    }
}

Screenshot


Source : http://www.aspsnippets.com/

No comments:

Post a Comment

Join US Our Community
×