views:

23

answers:

1

While I was trying to play with Pagination Support in Repeater, PagedDataSource rescued me. I made the following method and would like to share with all of you whether there is any pitfall or is there any chance for more improvement.

Here it is,

/// <summary>
/// Create pagination for Repeater
/// </summary>
/// <param name="context">HttpContext</param>
/// <param name="obj">System.Collections.IEnumerable</param>
/// <param name="rptr">Repeater Control</param>
/// <param name="pgSize">How many records in each page</param>
/// <returns>Pagination String</returns>
public static String pagination(HttpContext context,Object obj,Repeater rptr ,int pgSize )
{
    String rtn = String.Empty;

    int curpage = 0;

    PagedDataSource pds = new PagedDataSource();
    pds.DataSource=(System.Collections.IEnumerable)obj;
    pds.AllowPaging = true;
    pds.PageSize = pgSize;

    if (context.Request.QueryString["page"] != null)
    {
        curpage = Convert.ToInt32(context.Request.QueryString["page"]);
    }
    else
    {
        curpage = 1;
    }

    pds.CurrentPageIndex = curpage - 1;

    if (!pds.IsFirstPage)
    {
        rtn = "<a href='?page=" + (curpage - 1).ToString() + "'>Prev</a>&nbsp;";
    }

    if (curpage == 1 && pds.DataSourceCount > pds.PageSize)
        rtn = "1";
    else if (pds.DataSourceCount == 0)
        rtn = "No data to display";
    else if (curpage > 1 && pds.DataSourceCount > pds.PageSize)
        rtn = rtn + "<a href='?page=1'>1</a>&nbsp;";

    for (int i = 2; i <= pds.PageCount; i++)
    {
        if (i == curpage)
            rtn = rtn + "&nbsp;" + i.ToString();
        else
            rtn = rtn + "&nbsp;<a href='?page=" + i.ToString() + "'>" + i.ToString() + "</a>";
    }

    if (!pds.IsLastPage)
    {
        rtn += "&nbsp;<a href='?page=" + (curpage + 1).ToString() + ">Next</a>";
    }

    rptr.DataSource = pds;
    rptr.DataBind();

    return rtn;
}
A: 

I can see some in terms of best practice but your structure is pretty sound. However, may I suggest the following:

1) I would suggest code guards.

2) Inline formating (using the + operator to build a string) is more costly than String.Format() method.

3) Never use Convert.ToInt32() as it can cause the code to bail. Please use Int32.TryParse() as it is safer.

4) Also, you might want to look at the concept of Url Routing or Url Rewriting to make your urls more friendly.

Carnotaurus
Thank you so much. What is code guards?
Hoque
An example of a code guard is something like a null check. This check that an object is not null before you assign values to its propeties - don't forget to vote
Carnotaurus