Introduction
In this article i will explain about how to save image in folder and display or bind in DataList. In few simple steps you can achieve this task.Create New-WebSite and then select a New-Folder name it as Images.Go to Solution Explorer click on Add and add a New WebForm in your application. Now use following code on your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Images to Datalist from folder</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" onclick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dlImage" runat="server" RepeatColumns="4" 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="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>
Right click on aspx page and Click on View Code. Use following code on Code-behind Window
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dlImage.DataSource = listItems;
dlImage.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
fileupload1.SaveAs(Server.MapPath("Images/" +
filename));
BindDataList();
}
No need of database , just save the image directly to folder and display in Grid, DataList as per your need. Hope you enjoy the code.
0 comments:
Post a Comment