Tags
Here is the simple custom webpart which random displays the image from picture library.
You can edit the web part by change the URL and picture library name
public class RandomImage : System.Web.UI.WebControls.WebParts.WebPart { string _SiteURL = SPContext.Current.Web.Url; string _PicLibName = "Pic Lib"; [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), FriendlyName("The Site URL of Picture Library")] public string SiteURL { get { return _SiteURL; } set { _SiteURL = value; } } [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), FriendlyName("The Name of Picture Library")] public string PicLibName { get { return _PicLibName; } set { _PicLibName = value; } } Image myimage = new Image(); protected override void CreateChildControls() { myimage.Height = 256; myimage.Width = 256; try { using (SPSite mysite = new SPSite(SiteURL)) { //mysite = SPControl.GetContextSite(Context); using (SPWeb myweb = mysite.OpenWeb()) { SPList mylist = myweb.Lists[PicLibName]; SPQuery myquery = new SPQuery(); myquery.Query = ""; string serverpath = mysite.Url.ToString() + "/"; SPListItemCollection mylistitem = mylist.GetItems(myquery); if (mylistitem.Count > 0) { System.Random RandNum = new System.Random(); int MyRandomNumber = RandNum.Next(mylistitem.Count); myimage.ImageUrl = serverpath + mylistitem[MyRandomNumber].Url.ToString(); } else { this.Page.Response.Write("No image found"); } } } } catch (Exception ex) { Controls.Clear(); Label errorMessage = new Label(); errorMessage.Text = "There was an error in the code. Please contact your system administrator and rely the following " + "message: " + ex.Message; Controls.Add(errorMessage); } base.CreateChildControls(); } protected override void Render(HtmlTextWriter writer) { myimage.RenderControl(writer); // TODO: add custom rendering code here. // writer.Write("Output HTML"); } }
Frank O'Sullivan said:
Hi, I’m sorry but I’m a complete newbie.
Can I just save this script to a file and import into sharepoint?
If you have time, it would be great to get some simple instructions on how to get it working.
Frank
ridwan sassman said:
Hi Liedong;
Thanks for the great post; however I need to add a link to each image in the image rotator. WOuld you have any ideas or clues to get me quickly started?
Thanks
TexasT said:
Very nice and simple. Thank you…you saved me some coding time!
Dora said:
I’ve been browsing on-line more than 3 hours nowadays, but I never found any fascinating article like yours. It is lovely price enough for me. In my view, if all webmasters and bloggers made good content material as you probably did, the web might be much more useful than ever before.