Reputation: 779
My asp markup is as follows:
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5" OnItemDataBound="dtlist_DataBound">
<ItemTemplate>
<asp:Image Width="150" ID="Image1" ImageUrl='<%# Container.DataItem %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink12" Text='<%# Container.DataItem %>' NavigateUrl='<%# Container.DataItem %>' runat="server"/>
</ItemTemplate>
</asp:DataList>
My c# code is as follows:
protected void dtlist_DataBound(object sender, DataListItemEventArgs e)
{
string albumName = Context.Request.QueryString["Album"];
try
{
DirectoryInfo dir = new DirectoryInfo(MapPath(string.Format("Images/{0}", albumName)));
FileInfo[] files = dir.GetFiles();
foreach (FileInfo info in files)
{
((Image)e.Item.FindControl("Image1")).ImageUrl = string.Format("~/Images/{0}/{1}", albumName, info.Name);
((HyperLink)e.Item.FindControl("HyperLink12")).Text = info.Name;
((HyperLink)e.Item.FindControl("HyperLink12")).NavigateUrl = string.Format("~/Images/{0}/{1}", albumName, info.Name);
}
}
catch (Exception ex)
{
throw;
}
}
I want to display the images from the particular folder(album) stored in the disk drive. When user will click album 1, all the images from album1 will be shown. For eg. if album1 contains 10 images, then 10 images should be displayed in datalist. But from my above code, only the last image is displayed in all 10 images. Is there any way to modify the above code to display 10 separate images?
Upvotes: 1
Views: 5942
Reputation: 1355
You shouldn't need the on item databound here, you could change your markup like this;
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image Width="150" ID="Image1" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Image") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink12" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Image") %>' runat="server"/>
</ItemTemplate>
</asp:DataList>
And in your page load, you could select a new list of anonymous type with the property names you desire (as stated in the markup as <%# DataBinder.Eval(Container.DataItem, "Name") %>:
string albumName = Context.Request.QueryString["Album"];
try
{
DirectoryInfo dir = new DirectoryInfo(MapPath(string.Format("Images/{0}", albumName)));
var dataToBeBound = dir.GetFiles().Select(x => new
{
Name = x.Name,
Image = string.Format("~/Images/{0}/{1}", albumName, x.Name)
}).ToList();
dtlist.DataSource = dataToBeBound;
dtList.DataBind();
}
catch (Exception ex)
{
throw;
}
Upvotes: 1