Wednesday, December 17, 2008

Implementing Paging in Datalist

Hi,
To implement paging concept in DataList use the following coding.
Here PagedDataSource is used to do paging in DataList.
Consider u r having one label named lblPagingTop to list no.of.records per page(eg. 2/6),
two hyperlinks topNextHyperLink,topPrevHyperLink for Paging.


In Code-behind have the following,

public void sampleStudPaging()
{
PagedDataSource sampleStudPagedDataSource = new PagedDataSource();
int currentPage;
try
{
if (sampleStuds.Length == 0)
{
topPrevHyperLink.Visible = false;
topNextHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (sampleStuds.Length > 0)
{
sampleStudPagedDataSource.DataSource = sampleStuds;
sampleStudPagedDataSource.PageSize = 2;
sampleStudPagedDataSource.AllowPaging = true;
if (Request.QueryString["p"] != null)
{
currentPage = int.Parse(Request.QueryString["p"].ToString());
}
else
{
currentPage = 1;
}
sampleStudPagedDataSource.CurrentPageIndex = currentPage - 1;
if (!sampleStudPagedDataSource.IsFirstPage)
{
topPrevHyperLink.NavigateUrl = Request.CurrentExecutionFilePath + "?p=" + Convert.ToInt32(currentPage - 1);
}
else
{
topPrevHyperLink.NavigateUrl = "#";
}
if (!sampleStudPagedDataSource.IsLastPage)
{
topNextHyperLink.NavigateUrl = Request.CurrentExecutionFilePath + "?p=" + Convert.ToInt32(currentPage + 1);
}
else
{
topNextHyperLink.NavigateUrl = "#";
}
lblTopPaging.Text = "Page: " + (currentPage).ToString() + " of " + sampleStudPagedDataSource.PageCount.ToString();
SampleStudDataList.DataSource = sampleStudPagedDataSource;
SampleStudDataList.DataBind();
if (currentPage == 1)
{
topPrevHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (currentPage == sampleStudPagedDataSource.PageCount)
{
topNextHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (sampleStudPagedDataSource.PageCount == 1)
{
topPrevHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
}
}
catch (Exception ex)
{
}
}

No comments: