Introduction
I often have the need to show pictures with captions as seen above.
My objective is to be able to do so dynamically, so that all I need to do is to create a folder on my PC whose name equals the title of the page ("Sample Pictures" in the image above), name the pictures with the words that appear in the captions and be able to sort the pictures in a specified order.
Using the Code
The code is quite simple:
The DisplayAlbum.aspx page includes a DataList, dlPhotos, whose DataSource is set to an instance of class PhotosDir in the Page_Load event:
PhotosDir pd = new PhotosDir();
dlPhotos.DataSource = pd.GetPhotos(Path);
dlPhotos.DataBind();
The GetPhotos()
method within the PhotosDir
class, simply returns a list of files within the given folder
public IList<fileinfo> GetPhotos(string Path)
{
MyList.Clear();
DirectoryInfo di = new DirectoryInfo(Path);
foreach (FileInfo fi in di.GetFiles())
{
MyList.Add(fi);
}
return MyList;
}
Preparing your Album
- Create a folder on your system. The name of the folder will be the name displayed as the title of the Album both in the browser title and within the HTML
- Copy the images you want to display to your new folder
- Rename the images so that they follow this format: {0}`{1}.{2}
For example: 04`Hydrangeas.jpg
{0} determines the sorting order of the picture. It is best to use at least two digits!
{1} becomes the caption
{2} is the extension of the picture (jpg, gif, etc)
Note that there should only be one each of the symbols ` and . for this to work properly - Redirect to the DisplayAlbum.aspx page, passing the folder name within the query string.
For example: Response.Redirect("DisplayAlbum.aspx?folder=Sample Pictures" );
In the attached zip file I suggest a more elegant way of calling the album from a button.
Finally, to extract the caption from the file name, the Split()
function comes in handy:
protected string PicName(string Name)
{
char[] Punctuation = { '.', '`' };
return Name.Split(Punctuation)[1];
}
Enjoy!