Wednesday, June 1, 2011

Displaying paged discussion board

Scenario:
We were working on to display item from a discussion list from a paged result set.

Solution:
While I am still not 100% convinced why someone need to fetch all records from 1 to last record of the page you want to display.

Here's the code which worked. Once can use this to work with cache object to make performance faster.

Code:

  public override void RenderControl (System.Web.UI.HtmlTextWriter writer)
{
writer.WriteLine("============================");

if (null != HttpContext.Current.Request.QueryString["pageno"])
{
int pageno = 1;
int.TryParse(HttpContext.Current.Request.QueryString["pageno"].ToString(), out pageno);

SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["Team Discussion"];

SPQuery oQuery = new SPQuery();
oQuery.RowLimit = 2;
oQuery.Query = "<OrderBy Override='TRUE'>" +
"<FieldRef Name='Modified' Ascending='FALSE' /></OrderBy>";

int intIndex = 1;

do
{
writer.WriteLine("Page: " + intIndex );

SPListItemCollection collListItems = oList.GetItems(oQuery);

if (intIndex == pageno)
{
foreach (SPListItem oListItem in collListItems)
{
writer.WriteLine(SPEncode.HtmlEncode(oListItem["Title"].ToString()) );
}

break;
}

oQuery.ListItemCollectionPosition = collListItems.ListItemCollectionPosition;
if (null != collListItems.ListItemCollectionPosition)

intIndex++;

} while (oQuery.ListItemCollectionPosition != null);

writer.Write("=================================");
}

base.RenderControl(writer);
}
Article: SPListItemCollectionPosition

0 comments: