Saturday 9 February 2013

Paging With SPListItemCollectionPosition

During search about how to implement custom paging in SharePoint List i found many articles like:

http://blogs.msdn.com/b/colbyafrica/archive/2009/02/19/learning-sharepoint-part-vi-list-pagination.aspx

while reading the above article i saw comment from a guy 

Similar example with source code
Step by Step Guide to implement Paging and sorting with SPQuery and SPListItemCollectionPosition

but when i went there (Similar example with source code) and start reading and applying the code i found that there is problem in Previous button and it's not working probably so i start changing the code :





  1. Next and Previous is working very well
  2. sorting using gridview sorting(not dropdownlist)
  3. You can use it without sorting columns ( just remove the  OnSorting="gvTasks_OnSorting") from html Code

Note: to runt the code you must has a List with name Tasks and columns:
  1. Title
  2. Status
  3. StartDate


Here is the Code:


<%--HTML Code--%>

<SharePoint:SPGridView ShowFooter="true" runat="server" AllowSorting="true" OnSorting="gvTasks_OnSorting"  ID="gvTasks" AllowPaging="true"
    PageSize="4" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Title" SortExpression="Title" HeaderText="Task Name" />
        <asp:BoundField DataField="Status" SortExpression="Status" HeaderText="TaskStatus" />
        <asp:BoundField DataField="StartDate" HeaderText="Start Date" />
    </Columns>
</SharePoint:SPGridView>

<table style="float:right; width:100px">
    <tr>
        <td>
            <asp:LinkButton ID="LinkButtonPrevious" runat="server"
                onclick="LinkButtonPrevious_Click"><<</asp:LinkButton>
        </td>
        <td>
           <asp:Label ID="LabelPaging" runat="server" Text="Label"></asp:Label></td>
        <td>
            <asp:LinkButton ID="LinkButtonNext" runat="server"
                onclick="LinkButtonNext_Click">>></asp:LinkButton>
        </td>
    </tr>
</table>



<C# code>

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadData(1,false);
            }
        }

        private void LoadData(int currentPage , bool isPrevious)
        {
            ViewState["CurrentPage"] = currentPage;

            string SortExpression = "";
            if (ViewState["SortExpression"] != null)
            {
                SortExpression = ViewState["SortExpression"] as string;
            }

            SortDirection sortDirection = SortDirection.Descending;
            //SortDirection sortDirection
            if (ViewState["SortDirection"] != null)
            {
                sortDirection = (SortDirection)ViewState["SortDirection"];
            }

            string pageInfo = ViewState["Next"] as string;
            if (isPrevious)
            {
                pageInfo = ViewState["Previous"] as string;
            }

            FillData(pageInfo, SortExpression, sortDirection == SortDirection.Ascending);
        }

        private void FillData(string pagingInfo, string sortColumn, bool sortAscending)
        {
            int currentPage = Convert.ToInt32(ViewState["CurrentPage"]);
            uint rowCount = (uint)gvTasks.PageSize;
            string columnValue = "";
            string nextPageString = "Paged=TRUE&p_ID={0}&p_" + sortColumn + "={1}";

            string PreviousPageString = "Paged=TRUE&PagedPrev=TRUE&p_ID={0}&p_" + sortColumn + "={1}";

            SPListItemCollection collection;

            //first make a call to fetch the desired result set
            //here is the actual call to the dal function
            collection = GetTestItems(sortColumn, sortAscending, pagingInfo, rowCount);
            DataTable objDataTable = collection.GetDataTable();
            gvTasks.DataSource = objDataTable;
            gvTasks.DataBind();

            //now we need to identify if this is a call from next or first

            if (null != collection.ListItemCollectionPosition)
            {
                if (!string.IsNullOrEmpty(sortColumn))
                {
                    if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[collection.Count - 1][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                    }
                    else
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToString(collection[collection.Count - 1][sortColumn]));
                    }                    
                }
                nextPageString = string.Format(nextPageString, collection[collection.Count - 1].ID, columnValue);
            }
            else
            {
                nextPageString = string.Empty;
            }

            if (currentPage > 1)
            {
                if (!string.IsNullOrEmpty(sortColumn))
                {
                    if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[0][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
                    }
                    else
                    {
                        columnValue = SPEncode.UrlEncode(Convert.ToString(collection[0][sortColumn]));
                    }                    
                }
                PreviousPageString = string.Format(PreviousPageString, collection[0].ID, columnValue);
            }
            else
            {
                PreviousPageString = string.Empty;
            }


            if (string.IsNullOrEmpty(nextPageString))
            {
                LinkButtonNext.Visible = false;
            }
            else
            {
                LinkButtonNext.Visible = true;
            }
            if (string.IsNullOrEmpty(PreviousPageString))
            {
                LinkButtonPrevious.Visible = false;
            }
            else
            {
                LinkButtonPrevious.Visible = true;
            }

            ViewState["Previous"] = PreviousPageString;
            ViewState["Next"] = nextPageString;
            LabelPaging.Text = ((currentPage - 1) * rowCount) + 1 + " - " + currentPage * rowCount;
        }

        protected void LinkButtonPrevious_Click(object sender, EventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CurrentPage"]) - 1,true);
        }

        protected void LinkButtonNext_Click(object sender, EventArgs e)
        {
            LoadData(Convert.ToInt32(ViewState["CurrentPage"]) + 1,false);
        }

        public static SPListItemCollection GetTestItems(string sortBy, bool sortAssending, string pagingInfo, uint rowLimit)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPListItemCollection collection;
            SPQuery objQuery = new SPQuery();
            objQuery.RowLimit = rowLimit;
            if (!string.IsNullOrEmpty(sortBy))
            {
                objQuery.Query = "<OrderBy><FieldRef Name='" + sortBy + "' Ascending='" + sortAssending + "' /></OrderBy>";
            }
            objQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='Status' /><FieldRef Name='StartDate' />";
            if (!string.IsNullOrEmpty(pagingInfo))
            {
                SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingInfo);
                objQuery.ListItemCollectionPosition = position;
            }

            collection = objWeb.Lists["Tasks"].GetItems(objQuery);
            return collection;
        }

        protected void gvTasks_OnSorting(object sender, GridViewSortEventArgs arg)
        {
            ViewState.Remove("Previous");
            ViewState.Remove("Next");
            //Ascending
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = arg.SortDirection;
            }
            else
            {
                ViewState["SortDirection"] = ((SortDirection)ViewState["SortDirection"] == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
            }
            ViewState["SortExpression"] = arg.SortExpression;
            LoadData(1,false);
        }







1 comment: