Display random item from list

By Alon Havivi

Get random item from SharePoint list

This web part display random task item from the Tasks list

using System;

using System.Collections.Generic;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

namespace ShowRandomItem

{

[Guid("faeeb9de-4724-48eb-a0df-72decafcd4e4")]

public class ShowRandomItem : Microsoft.SharePoint.WebPartPages.WebPart

{

public ShowRandomItem()

{

this.ExportMode = WebPartExportMode.All;

}

protected override void CreateChildControls()

{

base.CreateChildControls();

SPList list = SPContext.Current.Web.Lists["Tasks"];

Random random = new Random();

int index = random.Next(0, list.ItemCount - 1);

this.Controls.Add(new LiteralControl(list.Items[index]["Title"].ToString()));

}

}

}



Download the complete web part

Display random item from list  (1180 Views)
Create New Account