using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web;
using System.Text;
using System.IO;
using AspNetForums.Components;
using AspNetForums.Components.Enumerations;
namespace AspNetForums.Controls
{
public class PagerEventArgs : EventArgs
{
public PagerEventArgs()
{ }
public PagerEventArgs(int index)
{
newPageIndex = index;
}
public int NewPageIndex
{
get { return newPageIndex; }
}
int newPageIndex;
}
/// <summary>
/// Summary description for Pager.
/// </summary>
public class Pager : Label, INamingContainer
{
#region Member variables
HyperLink previousLink;
HyperLink nextLink;
HyperLink firstLink;
HyperLink lastLink;
HyperLink[] pagingHyperLinks;
bool urlPaging = true;
LinkButton previousButton;
LinkButton nextButton;
LinkButton firstButton;
LinkButton lastButton;
LinkButton[] pageingButtons;
HtmlInputText txtCustom;
Button button;
public Pager()
{
}
#endregion
PagerType pagerType = PagerType.None;
public PagerType PagerType
{
get { return pagerType; }
set { pagerType = value; }
}
#region Render functions
/// <summary>
/// This event handler adds the children controls and is resonsible
/// for determining the template type used for the control.
/// </summary>
protected override void CreateChildControls()
{
//AutoBindForTotalRecordsValue();
Controls.Clear();
if (UrlPaging)
{
AddPageLinks();
AddPreviousNextLinks();
AddFirstLastLinks();
}
else
{
AddPageButtons();
AddPreviousNextButton();
AddFirstLastButton();
}
AddCustomPager();
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "customPager", GetScripts(), true);
}
String GetScripts()
{
StringBuilder sb = new StringBuilder();
sb.Append(@"
function go(page){
if(event.keyCode==13||event.srcElement.value=='Go'){
var strUrl=location.href.toLowerCase();
strUrl=strUrl.replace(/(\&)?pageindex=\d+/gi,'');
if(location.search=='')
strUrl=strUrl+'?pageindex='+page;
else
strUrl=strUrl+'&pageindex='+page;
location.href=strUrl;
return false;
}
}");
return sb.ToString();
}
void AddCustomPager()
{
txtCustom = new HtmlInputText();
txtCustom.ID = "txtCustom";
txtCustom.EnableViewState = false;
txtCustom.Style.Add("width", "20px;");
txtCustom.Style.Add("border", "1px solid");
txtCustom.Attributes.Add("onkeyup", "this.value=this.value.replace(/[^0-9]/gi,'');");
Controls.Add(txtCustom);
button = new Button();
button.ID = "button";
button.Text = "Go";
button.Style.Add("width", "22px");
if (UrlPaging)
{
txtCustom.Attributes.Add("onkeydown", "return go(this.value);");
button.UseSubmitBehavior = false;
button.OnClientClick = "return go(document.getElementById('"+txtCustom.ClientID+"').value);";
}
else
{
button.Click += new EventHandler(LinkButton_Click);
}
Controls.Add(button);
}
protected override void Render(HtmlTextWriter writer)
{
int totalPages = CalculateTotalPages();
// Do we have data?
//
if (totalPages <= 1)
return;
if (ShowCurrentPage)
RenderCurrentPage(writer);
AddAttributesToRender(writer);
// Render the paging buttons
//
writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass, false);
// Render the first button
//
RenderFirst(writer);
// Render the previous button
//
RenderPrevious(writer);
// Render the page button(s)
//
RenderPagingButtons(writer);
// Render the next button
//
RenderNext(writer);
// Render the last button
//
RenderLast(writer);
RenderCustom(writer);
}
void RenderCustom(HtmlTextWriter writer)
{
writer.Write(" 跳转到:");
txtCustom.RenderControl(writer);
button.RenderControl(writer);
}
void RenderCurrentPage(HtmlTextWriter writer)
{
writer.Write(string.Format(this.CurrentPageStringFormat, (this.PageIndex + 1), this.CalculateTotalPages(), this.TotalRecords));
}
void RenderFirst(HtmlTextWriter writer)
{
int totalPages = CalculateTotalPages();
if ((PageIndex >= 3) && (totalPages > 5))
{
if (UrlPaging)
{
firstLink.RenderControl(writer);
}
else
{
firstButton.RenderControl(writer);
}
LiteralControl l = new LiteralControl(" ... ");
l.RenderControl(writer);
}
}
void RenderLast(HtmlTextWriter writer)
{
int totalPages = CalculateTotalPages();
if (((PageIndex + 3) < totalPages) && (totalPages > 5))
{
LiteralControl l = new LiteralControl(" ... ");
l.RenderControl(writer);
if (UrlPaging)
{
lastLink.RenderControl(writer);
}
else
{
lastButton.RenderControl(writer);
}
}
}
void RenderPrevious(HtmlTextWriter writer)
{
Literal l;
if (HasPrevious)
{
if (UrlPaging)
{
previousLink.RenderControl(writer);
}
else
{
previousButton.RenderControl(writer);
}
l = new Literal();
l.Text = " ";
l.RenderControl(writer);
}
}
void RenderNext(HtmlTextWriter writer)
{
Literal l;
if (HasNext)
{
l = new Literal();
l.Text = " ";
l.RenderControl(writer);
if (UrlPaging)
{
nextLink.RenderControl(writer);
}
else
{
nextButton.RenderControl(writer);
}
}
}
void RenderButtonRange(int start, int end, HtmlTextWriter writer)
{
for (int i = start; i < end; i++)
{
// Are we working with the selected index?
//
if (PageIndex == i)
{
// Render different output
//
Literal l = new Literal();
l.Text = "<b>" + (i + 1).ToString() + "</b>";
l.RenderControl(writer);
}
else
{
if (UrlPaging)
{
pagingHyperLinks[i].RenderControl(writer);
}
else
{
pageingButtons[i].RenderControl(writer);
}
}
if ( i < (end - 1) )
writer.Write(" ");
}
}
void RenderPagingButtons(HtmlTextWriter writer)
{
int totalPages;
// Get the total pages available
//
totalPages = CalculateTotalPages();
// If we have <= 5 pages display all the pages and exit
//
if ( totalPages <= 5)
{
RenderButtonRange(0, totalPages, writer);
}
else
{
int lowerBound = (PageIndex - 2);
int upperBound = (PageIndex + 3);
if (lowerBound <= 0)
lowerBound = 0;
if (PageIndex == 0)
RenderButtonRange(0, 5, writer);
else if (PageIndex == 1)
RenderButtonRange(0, (PageIndex + 4), writer);
else if (PageIndex < (totalPages - 2))
RenderButtonRange(lowerBound, (PageIndex + 3), writer);
else if (PageIndex == (totalPages - 2))
RenderButtonRange((totalPages - 5), (PageIndex + 2), writer);
else if (PageIndex == (totalPages - 1))
RenderButtonRange((totalPages - 5), (PageIndex + 1), writer);
}
}
#endregion
#region ControlTree functions
void AddPageLinks()
{
// First add the lower page buttons
//
pagingHyperLinks = new HyperLink[CalculateTotalPages()];
// Create the buttons and add them to
// the Controls collection
//
for (int i = 0; i < pagingHyperLinks.Length; i++)
{
pagingHyperLinks[i] = new HyperLink();
pagingHyperLinks[i].EnableViewState = false;
pagingHyperLinks[i].Text = (i + 1).ToString();
pagingHyperLinks[i].ID = (i + 1).ToString();
pagingHyperLinks[i].NavigateUrl = CreatePagerURL((i + 1).ToString());
Controls.Add(pagingHyperLinks[i]);
}
}
void AddPageButtons()
{
pageingButtons = new LinkButton[CalculateTotalPages()];
for (int i = 0; i < pageingButtons.Length; i++)
{
pageingButtons[i] = new LinkButton();
pageingButtons[i].EnableViewState = false;
pageingButtons[i].Text = (i + 1).ToString();
pageingButtons[i].ID = (i + 1).ToString();
pageingButtons[i].CommandArgument = i.ToString();
pageingButtons[i].Click += new EventHandler(LinkButton_Click);
Controls.Add(pageingButtons[i]);
}
}
void AddFirstLastLinks()
{
int start = 1;
firstLink = new HyperLink();
firstLink.ID = "First";
firstLink.Text = this.FirstPageText;
firstLink.NavigateUrl = CreatePagerURL(start.ToString());
Controls.Add(firstLink);
int last = CalculateTotalPages();
lastLink = new HyperLink();
lastLink.ID = "Last";
lastLink.Text = this.LastPageText;
lastLink.NavigateUrl = CreatePagerURL(last.ToString());
Controls.Add(lastLink);
}
void AddFirstLastButton()
{
int start = 0;
firstButton = new LinkButton();
firstButton.ID = "First";
firstButton.Text = this.FirstPageText;
firstButton.CommandArgument = start.ToString();
firstButton.Click+=new EventHandler(LinkButton_Click);
Controls.Add(firstButton);
lastButton = new LinkButton();
lastButton.ID = "Last";
lastButton.Text = this.LastPageText;
lastButton.CommandArgument = (CalculateTotalPages()-1).ToString();
lastButton.Click+=new EventHandler(LinkButton_Click);
Controls.Add(lastButton);
}
void AddPreviousNextLinks()
{
int previous;
if (this.PageIndex < 2)
previous = 1;
else
previous = this.PageIndex;
previousLink = new HyperLink();
previousLink.ID = "Prev";
previousLink.Text = this.PreviousPageText;
previousLink.NavigateUrl = CreatePagerURL(previous.ToString());
Controls.Add(previousLink);
int next = this.PageIndex + 2;
nextLink = new HyperLink();
nextLink.ID = "Next";
nextLink.Text = this.NextPageText;
nextLink.NavigateUrl = CreatePagerURL(next.ToString());
Controls.Add(nextLink);
}
void AddPreviousNextButton()
{
int previous;
if (this.PageIndex < 2)
previous = 1;
else
previous = this.PageIndex-1;
previousButton = new LinkButton();
previousButton.ID = "Prev";
previousButton.Text = this.PreviousPageText;
previousButton.CommandArgument = previous.ToString();
previousButton.Click+=new EventHandler(LinkButton_Click);
Controls.Add(previousButton);
int next = previous + 2;
nextButton = new LinkButton();
nextButton.ID = "Next";
nextButton.Text = this.NextPageText;
nextButton.CommandArgument = next.ToString();
nextButton.Click+=new EventHandler(LinkButton_Click);
Controls.Add(nextButton);
}
#endregion
#region Properties
/// <summary>
/// Override how this control handles its controls collection
/// </summary>
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
private bool HasPrevious
{
get
{
if (PageIndex > 0)
return true;
return false;
}
}
private bool HasNext
{
get
{
if (PageIndex + 1 < CalculateTotalPages() )
return true;
return false;
}
}
private bool IsBoundUsingDataSourceID
{
get
{
return (this.DataSourceID.Length > 0);
}
}
bool showCurrentPage = true;
public bool ShowCurrentPage
{
get { return showCurrentPage; }
set { showCurrentPage = value; }
}
public bool UrlPaging
{
get { return urlPaging; }
set { urlPaging = value; }
}
string currentPageStringFormat="";// = "Page {0} of {1} ({2} records) - ";
/// <summary>
/// CurrentPageStringFormat is the text that should be used to dispaly current page number.
/// It has been provided to allow custom formatting.
/// There are 2 implicit params that you may use: page index and total pages number.
/// Its implicit format is: "Page {0} of {1} ({2} records) - " and it makes use of both params.
/// </summary>
public string CurrentPageStringFormat
{
get { return currentPageStringFormat; }
set { currentPageStringFormat = value; }
}
string dataSourceID = string.Empty;
public string DataSourceID
{
get
{
object obj1 = ViewState["DataSourceID"];
if (obj1 != null)
{
dataSourceID = (string)obj1;
}
return dataSourceID;
}
set
{
dataSourceID = value;
ViewState["DataSourceID"] = dataSourceID;
}
}
string firstPageText = "<<";
public string FirstPageText
{
get { return firstPageText; }
set { firstPageText = value; }
}
string lastPageText = ">>";
public string LastPageText
{
get { return lastPageText; }
set { lastPageText = value; }
}
string previousPageText = "<";
public string PreviousPageText
{
get { return previousPageText; }
set { previousPageText = value; }
}
string nextPageText = ">";
public string NextPageText
{
get { return nextPageText; }
set { nextPageText = value; }
}
int _pageIndex = 0;
public virtual int PageIndex
{
get
{
if (!UrlPaging)
{
if (ViewState["PageIndex"] == null)
return 0;
else
return Convert.ToInt32(ViewState["PageIndex"]);
}
else
{
_pageIndex = ForumContext.Current.PageIndex;
if (_pageIndex < 0)
return 0;
else
return _pageIndex;
}
}
set
{
ViewState["PageIndex"] = value;
_pageIndex = value;
}
}
public virtual int PageSize
{
get
{
int pageSize = Convert.ToInt32(ViewState["PageSize"]);
SiteSettings settings = Globals.GetSiteSettings();
if (pageSize <= 0)
{
switch (pagerType)
{
case PagerType.ShowPost:
return settings.PostsPerPage;
case PagerType.ShowForum:
return settings.ThreadsPerPage;
case PagerType.None:
return settings.ThreadsPerPage;
}
}
return pageSize;
}
set
{
ViewState["PageSize"] = value;
}
}
public int TotalRecords
{
get
{
return Convert.ToInt32(ViewState["TotalRecords"]);
}
set
{
ViewState["TotalRecords"] = value;
}
}
#endregion
#region Helper methodss
protected virtual string CreatePagerURL(string pageIndex)
{
HttpContext context = HttpContext.Current;
SiteUrls siteUrl = new SiteUrls();
switch (pagerType)
{
case PagerType.ShowPost:
int postID = 0;
try
{
postID = int.Parse(context.Request.QueryString["PostID"]);
}
catch { }
return siteUrl.Post(postID, int.Parse(pageIndex));
case PagerType.ShowForum:
int forumID = 0;
try{
forumID = int.Parse(context.Request.QueryString["ForumID"]);
}
catch {}
return siteUrl.Forum(forumID, int.Parse(pageIndex));
case PagerType.LatestTopics:
return siteUrl.PostsLatest(int.Parse(pageIndex));
case PagerType.NotReadTopics:
return siteUrl.PostsNotRead(int.Parse(pageIndex));
case PagerType.UnansweredTopics:
return siteUrl.PostsUnanswered(int.Parse(pageIndex));
case PagerType.ActiveTopics:
return siteUrl.PostsActive(int.Parse(pageIndex));
//case PagerType.PrivateMessages:
// return siteUrl.
case PagerType.None:
if (context.Request.Url.AbsoluteUri.IndexOf("?") == -1)
{
return context.Request.Url.AbsoluteUri.ToString() + "?PageIndex=" + pageIndex;
}
else
{
if (context.Request.Url.AbsoluteUri.ToLower().IndexOf("pageindex=") == -1)
return context.Request.Url.AbsoluteUri.ToString() + "&PageIndex=" + pageIndex;
else
{
//SiteUrls siteUrls = new SiteUrls();
//siteUrls.th
return Regex.Replace(context.Request.Url.AbsoluteUri.ToLower().ToString(), @"pageindex=(\d+\.?\d*|\.\d+)", "PageIndex=" + pageIndex);
}
}
}
return "";
}
/// <summary>
/// Static that caculates the total pages available.
/// </summary>
///
public virtual int CalculateTotalPages()
{
int totalPagesAvailable;
if (TotalRecords == 0)
return 0;
// First calculate the division
//
totalPagesAvailable = TotalRecords / PageSize;
// Now do a mod for any remainder
//
if ((TotalRecords % PageSize) > 0)
totalPagesAvailable++;
return totalPagesAvailable;
}
#endregion
public event EventHandler<PagerEventArgs> PageIndexChanged;
protected void OnPageIndexChanged(PagerEventArgs e)
{
this.PageIndex = e.NewPageIndex;
EventHandler<PagerEventArgs> eventHandler = PageIndexChanged;
if (eventHandler != null)
eventHandler(this, e);
}
void LinkButton_Click(object sender, EventArgs e)
{
int pageIndex = 0;
try
{
if (sender is LinkButton)
{
pageIndex = Convert.ToInt32((sender as LinkButton).CommandArgument);
}
else if (sender is Button)
{
pageIndex = Convert.ToInt32(txtCustom.Value)-1;
}
else
{
pageIndex = Convert.ToInt32((sender as TextBox).Text);
}
}
catch (InvalidCastException ex)
{
pageIndex = 0;
}
PagerEventArgs pe = new PagerEventArgs(pageIndex);
OnPageIndexChanged(pe);
}
}
}