Thursday, October 29, 2009

A simple SharePoint Random Picture Control

The following bit of code will display a random picture from the library "2009-10" (which must be a picture library) every time the page loads. This code can obviously be enhanced quite a bit (and it will be), but I thought I would start with something simple:


namespace DougsWebParts
{
     [Guid("c1eff21d-7467-4b5d-a696-0ecd5ae2d719")]
     public class PictureDisplayWebPart :
          System.Web.UI.WebControls.WebParts.WebPart
    {
          Random randomNumber;

          public PictureDisplayWebPart()
         {
                 randomNumber = new Random();
                 Load += new EventHandler(PictureDisplayWebPart_Load);
         }

         protected void PictureDisplayWebPart_Load(Object sender,
                 EventArgs e)
        {
                 Controls.Clear();
                 ClearChildState();
                 SPWeb thisWeb = SPContext.Current.Web;

                 SPPictureLibrary pictures =
                          (SPPictureLibrary)thisWeb.Lists["2009-10"];
                 int pictureCount = pictures.ItemCount;
                 int index = randomNumber.Next(pictureCount);

                 String itemHtml = String.Format(@"<img SRC=""{0}""" +
                          "height=""200px""> </img>",
                          thisWeb.Url + "/" + pictures.Items[index].Url);
                 this.Controls.Add(new LiteralControl(itemHtml));

        }
    }
}

No comments:

Post a Comment