Saturday, July 21, 2007

example | C# .NET ASP.NET| Binding image names from a filesystem to an ArrayList, and binding that to ASP.NET databound control

Intent: Sometimes you want to display photographs contained in a filesystem directly, without referencing  an intermediate data layer like a database store or XML file. You

Overview: Instantiate an ArrayList. Iterate over the output of the Directory.GetFiles() method, specifying the image extension as a mask. Build up HTML that should be placed in each cell of a databound control. Call the ArrayList's .Add method to write the HTML string to the ArrayList. Assign the Array as the DataSource of a DataList.  Bind that DataList to an <ItemTemplate> using the <%# Container.DataItem %>    syntax.  Call the DataList.DataBind(); method.

Discussion: The example below also allows the user to adjust the number of displayed columns via a DropDownList selection. This works by programmatically assigning the DataList.RepeatColumns property to the DropDownList.Selected property. 

        ArrayList pics = new ArrayList();

string code;
string image;
//string myFile;
foreach (string myFile in Directory.GetFiles(("T:\\WHATEVER\\WhateverSubDir"), "*.jpg"))
{
image = YOUR_DIRECTORY + Path.GetFileName(myFile);
code = "<img src=\"" + image + "\">";
code += "<br /> " + Path.GetFileName(myFile);
pics.Add(code); // add the image to your ArrayList
}
// Bind the pics to a DataList
dlImages.DataSource = pics;

dlImages.RepeatColumns = Convert.ToInt32(DropDownList1.SelectedValue);
dlImages.DataBind();
 
    <form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:ListItem Value="1">One column</asp:ListItem>
<asp:ListItem Value="2">Two Columns</asp:ListItem>
<asp:ListItem Value="3">Three Columns</asp:ListItem>
<asp:ListItem Value="4">Four Columns</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="dlImages" runat="server" RepeatColumns="5" RepeatDirection="Horizontal">
<ItemTemplate>
<%# Container.DataItem %>


</ItemTemplate>
<ItemStyle Font-Names="Arial" Font-Size="X-Small" />
</asp:DataList></div>
</form>

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home