Click here to Skip to main content
Licence CPOL
First Posted 19 Oct 2004
Views 60,958
Bookmarked 32 times

ShowImages: a usercontrol to display your web images

By | 19 Oct 2004 | Article
ShowImages is a simple usercontrol built to facilitate the display of your images/photos stored on web server.

Sample Image - ShowImages.jpg

Introduction

ShowImages is a simple user control built to facilitate the display of your images/photos stored on a web server.

Using the code

ShowImages is a simple user control built to facilitate image display. To see how this user control really works, please visit my site.

ShowImages shows thumbnails, generated by the page getThumbnail.aspx (included in the project), using a DataList. Using ShowImages properties, it is possible set up the Item DataList, and width and height of thumbnails.

Properties of ShowImages are displayed in the following code:

    // font properties
    // specify font family names (comma separated)
    // i.e.: verdana,serif
    // Arial Narrow,verdana
    public string FontName
    {
        set
        {
            fontName = value;
        }
    }

    // specify font size property
    // ie: 10px
    // xx-small
    public string FontSize
    {
        set
        {
            fontSize = value;
        }
    }

    public Boolean FontBold
    {
        set
        {
            fontBold = value;
        }
    }

    // thumbnails
    // height and width
    public int ThumbsHeight
    {
        set 
        {
            thumbnailHeight = value;
        }
    }

    public int ThumbsWidth
    {
        set 
        {
            thumbnailWidth = value;
        }
    }

    // decide how many columns must
    // have the image datalist
    public int Columns
    {
        set
        {
            columns = value;
        }
    }

    // set directory where to find images
    public string DefaultDir
    {
        set
        {
            imagespath = value;
        }
    }


    // set search pattern
    // multiple pattern must be separated by ";"
    // i.e.: *.jpg;*.gif
    public string SearchPattern
    {
        set
        {
            string [] split = null;

            split = value.Split(';');

            foreach (string s in split)
            {
                searchPatternList.Add(s);
            }
        }
    }

ShowImages uses the DefaultDir property to start to navigate inside your image directories. It shows images filtered by the SearchPattern property; if sub-directories are present, ShowImages shows folder entries so you can navigate them.

The following function fills the DataList with images' data.

    /// <SUMMARY>
    /// BuildImagesList
    /// create the image list and
    /// fill the datalist
    /// <PARAM />
    /// </SUMMARY>
    private void BuildImagesList()
    {
        // Create new DataTable objects.
        DataTable myDataTable = new DataTable();
        // Declare DataColumn and DataRow variables.
        DataColumn myColumn;
        DataRow myRow; 

        // Create new DataColumn, set DataType,
        // ColumnName and add to DataTable.    
        myColumn = new DataColumn();
        myColumn.DataType = System.Type.GetType("System.String");
        myColumn.ColumnName = "filename";
        myDataTable.Columns.Add(myColumn);

        // Create second column.
        myColumn = new DataColumn();
        myColumn.DataType = Type.GetType("System.Int32");
        myColumn.ColumnName = "type";
        myDataTable.Columns.Add(myColumn);


        physicalpath = Server.MapPath(imagespath);

        string[] dirList;
        try
        {
            dirList = Directory.GetDirectories(physicalpath);

            // it's a subdir of default dir
            // so I add a link to parent folder
            if (! isMainDir)
            {
                myRow = myDataTable.NewRow();
                myRow["filename"] = getParentDirName(imagespath);
                myRow["type"] = 0; 
                myDataTable.Rows.Add(myRow);
            }

            foreach (string s in Directory.GetDirectories(physicalpath))
            {
                myRow = myDataTable.NewRow();
                myRow["filename"] = addFolderToString(imagespath, 
                                            Path.GetFileName(s));
                myRow["type"] = 1; // directory
                myDataTable.Rows.Add(myRow);

            }

            for (int i=0; i < searchPatternList.Count; i++)
            {
                foreach (string s in Directory.GetFiles(physicalpath, 
                         searchPatternList[i].ToString()))
                {
                    myRow = myDataTable.NewRow();
                    myRow["filename"] = addFolderToString(imagespath, 
                                                Path.GetFileName(s));
                    myRow["type"] = 2; // file
                    myDataTable.Rows.Add(myRow);

                }
            }
            DataView sortedView = new DataView(myDataTable);
            sortedView.Sort = "type, filename asc";

            dlImages.RepeatColumns = columns;
            dlImages.DataSource = sortedView; 
            dlImages.DataBind();

            sortedView = null;
            myDataTable = null;
        }
        catch (Exception ex)
        {}
        finally
        {}

    }

User control DataList has the following item template:

    ...
    <ItemTemplate>
        <br>
        <a
        href="" runat= "server" id= "imgLink"><img runat="server" border="0" 
                id="imgThumbnail" align="middle">
        </a>
        <br>
        <asp:Label Runat="server" ID="imgName" Font-Bold="True" ></asp:Label>
    </ItemTemplate>
    ...

Which is filled with correct data using the ItemDataBound event:

    /// <SUMMARY>
    /// map ItemDataBound events to format
    /// correctly items
    /// </SUMMARY>
    /// <RETURNS></RETURNS>
    private void dlImages_ItemDataBound(Object sender, 
            System.Web.UI.WebControls.DataListItemEventArgs e)
    {
        System.Web.UI.HtmlControls.HtmlImage img = null;
        System.Web.UI.HtmlControls.HtmlAnchor imgLink = null;
        System.Web.UI.WebControls.Label imgName = null;

        //make sure this is an item in the data list (not header, ecc.)
        if ( (e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem) )
        {
            // get a reference to the image, link and label
            img = (System.Web.UI.HtmlControls.HtmlImage)
                  (e.Item.FindControl("imgThumbnail"));
            imgLink = (System.Web.UI.HtmlControls.HtmlAnchor)
                      (e.Item.FindControl("imgLink"));
            imgName = (System.Web.UI.WebControls.Label)
                      (e.Item.FindControl("imgName"));

            // if necessary set label font
            imgName.Font.Bold = fontBold;
            if ( fontName.Length > 0)
            {
                imgName.Font.Names = fontName.Split(',');
            }
            if (fontSize.Length > 0)
            {
                FontUnit fu = new FontUnit(fontSize);
                imgName.Font.Size = fu;
            }

            if ((((System.Data.DataRowView)
                  (e.Item.DataItem))[1]).ToString() == "0")
            {
                // format parent directory item
                imgLink.HRef = Request.Url.AbsolutePath + "?path=" + 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                img.Src = "cartella.bmp";
                imgName.Width = thumbnailWidth;
                imgName.Text = "..";
                img.Alt = "Come back to parent folder";
            }
            else if ((((System.Data.DataRowView)
                       (e.Item.DataItem))[1]).ToString() == "1")
            {
                // format directory items
                imgLink.HRef =  Request.Url.AbsolutePath  + "?path=" + 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                img.Src = "cartella.bmp";
                imgName.Text = getFileName((((System.Data.DataRowView)
                                           (e.Item.DataItem))[0]).ToString());
                img.Alt = "Click to explore dir\n" + imgName.Text;
            }
            else
            {
                // format file items
                imgLink.HRef = 
                  (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString();
                imgLink.Target = "_balnk";
                img.Src = "getThumbnail.aspx?img=" + 
                    (((System.Data.DataRowView)(e.Item.DataItem))[0]).ToString() + 
                    ((thumbnailHeight>0)?"&height="+ 
                      thumbnailHeight.ToString():"") + 
                    ((thumbnailWidth>0)?"&width="+ 
                      thumbnailWidth.ToString():"");
                imgName.Text = getFileName((((System.Data.DataRowView)
                                           (e.Item.DataItem))[0]).ToString());
                img.Alt = "Click to zoom\n" + imgName.Text;
            }
        }
    }

Using the user control is very easy. You have to insert a Register directive, and a code like the following, in your aspx page.

    ...
    <uc1:ShowImages id="ShowImages1" runat="server" 
        ThumbsHeight="100" ThumbsWidth="170" FontBold="false"
        FontSize="xx-small" FontName="verdana" 
        SearchPattern="*.jpg;*.gif" DefaultDir="/webimages">
    </uc1:showimages>
    ...

Note

Source code includes a Visual Studio Solution named "webalbum". Unzip it in your hard disk and create a web site, on port 8081, pointing to webalbum directory. That's all.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Massimo Beatini

Web Developer

Italy Italy

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralRegister TAG PinmemberLeonardo.Nakahara8:31 3 Mar '08  
QuestionHow to show an image title Pinmemberbruh_man9:01 18 Mar '05  
AnswerRe: How to show an image title Pinsussmbeatini6:04 21 Mar '05  
GeneralRe: How to show an image title Pinmemberbruh_man9:39 21 Mar '05  
GeneralRe: How to show an image title Pinsussmbeatini6:00 23 Mar '05  
GeneralRe: How to show an image title Pinsussmbeatini7:16 23 Mar '05  
GeneralRe: How to show an image title Pinmemberbruh_man8:30 23 Mar '05  
Thanks Massimo,
 
I have a question about step 1 of your instructions. On it you right clicked on something to get to properties. What was it? Confused | :confused:
GeneralRe: How to show an image title Pinsussmbeatini20:51 29 Mar '05  
GeneralPort 8081 PinmemberTBermudez8:47 19 Oct '04  
GeneralRe: Port 8081 Pinmembermbeatini20:39 19 Oct '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120528.1 | Last Updated 19 Oct 2004
Article Copyright 2004 by Massimo Beatini
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid