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
     public class PictureDisplayWebPart :
          Random randomNumber;

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

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

                 SPPictureLibrary pictures =
                 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