CSDN博客

img wind7788

发布分页控件源代码--组合控件

发表于2004/9/20 23:11:00  1890人阅读

分类: 技术文章

using System;
using System.IO;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace Pager
{
 /// <summary>
 /// coolPager 的摘要说明。
 /// </summary>
 public enum SortType
 {
  ASC=0,Desc=1
 };
 public enum IsCount
 {
  noReturnRecordCount=0,returnRecordCount
 };
 [DefaultProperty("copyRight"),
  ToolboxData("<{0}:coolPager runat=server></{0}:coolPager>")]
 public class coolPager : System.Web.UI.WebControls.WebControl,INamingContainer
 { 
  protected int recordCount=0;
  protected Control _controlToPaginate;
  protected PagedDataSource _dataSource;

  [Bindable(true),
   Category("Appearance"),
   DefaultValue("")]
  public string copyRight
  {
   get
   {
    return "版权所有:千山一鸟";
   }
  }
  //连接字符串
  [Description("数据源连接字符串"),DefaultValue("")]
  public string connectionString
  {
   get
   {
    object obj = ViewState["connectionString"];
    return (obj==null)?String.Empty:obj.ToString();
   }
   set
   {
    ViewState["connectionString"]=value;
   }
  }
  //显示分页的控件
  [Description("用于显示分页的控件"),DefaultValue("")]
  public string controlToPaginate
  {
   get
   {
    object obj=ViewState["controlToPaginate"];
    return (obj==null)?String.Empty:obj.ToString();
   }
   set
   {
    ViewState["controlToPaginate"]=value;
   }
  }
  //表名
  [Description("查询表名"),DefaultValue("")]
  public string tableName
  {
   get
   {
    Object obj=ViewState["tableName"];
    return (obj==null)?String.Empty:obj.ToString();
   }
   set
   {
    ViewState["tableName"]=value;
   }
  }
  //排序字段名
  [Description("排序字段"),DefaultValue("")]
  public string fieldName
  {
   get
   {
    Object obj=ViewState["fieldName"];
    return (obj==null)?String.Empty:obj.ToString();
   }
   set
   {
    ViewState["fieldName"]=value;
   }
  }
  //每页显示记录数
  [Description("每页记录数"),DefaultValue("")]
  public int pageSize
  {
   get
   {
    Object obj=ViewState["pageSize"];
    return (obj==null)?15:Convert.ToInt32(obj);
   }
   set
   {
    ViewState["pageSize"]=value;
   }
  }
  //页码
  [Description("当前页码"),DefaultValue("")]
  public int pageIndex
  {
   get
   {
    Object obj=ViewState["pageIndex"];
    return (obj==null)?1:Convert.ToInt32(obj);
   }
   set
   {
    ViewState["pageIndex"]=value;
   }
  }
  //是否返回记录总数
  [Description("是否返回记录总数"),DefaultValue("")]
  public IsCount isCount
  {
   get
   {
    return IsCount.returnRecordCount;
   }
  }
  //排序类型
  [Description("排序类型"),DefaultValue("")]
  public SortType sortType
  {
   get
   {
    Object obj=ViewState["sortType"];
    return (obj==null)?SortType.ASC:(SortType)obj;
   }
   set
   {
    ViewState["sortType"]=value;
   }
  }
  //Where子句
  [Description("where子句,不带where"),DefaultValue("")]
  public string Where
  {
   get
   {
    Object obj=ViewState["Where"];
    return (obj==null)?String.Empty:obj.ToString();
   }
   set
   {
    ViewState["Where"]=value;
   }
  }
  [Description("显示导航数字数"),DefaultValue("")]
  public int showPageNumber
  {
   get
   {
    Object obj=ViewState["showPageNumber"];
    return (obj==null)?10:Convert.ToInt32(obj);
   }
   set
   {
    ViewState["showPageNumber"]=value;
   }
  }
  [Description("开始页"),DefaultValue("")]
  public int pageStart
  {
   get
   {
    Object obj=ViewState["pageStart"];
    return (obj==null)?1:Convert.ToInt32(obj);
   }
   set
   {
    ViewState["pageStart"]=value;
   }
  }
  [Description("总页数,自动生成"),DefaultValue("")]
  public int pageCount
  {
   get
   {
    Object obj=ViewState["pageCount"];
    return (obj==null)?1:Convert.ToInt32(obj);
   }
   set
   {
    ViewState["pageCount"]=value;
   }
  }

  /// <summary>
  /// 将此控件呈现给指定的输出参数。
  /// </summary>
  /// <param name="output"> 要写出到的 HTML 编写器 </param>
  protected override void Render(HtmlTextWriter output)
  {
   if(Page.EnableViewState==false)
    Page.EnableViewState=true;
   if(Site!=null && Site.DesignMode)
    if(!Page.IsPostBack)
    CreateChildControls();
   base.Render(output);
  }
  public override void DataBind()
  {
   base.DataBind();

   ChildControlsCreated = false;

   if (controlToPaginate == "")
    return;
   _controlToPaginate = Page.FindControl(controlToPaginate);
   if (_controlToPaginate == null)
    return;
   if (!(_controlToPaginate is BaseDataList || _controlToPaginate is ListControl))
    return;

   if (connectionString == "" || tableName == "")
    return;

   // Fetch data
   FetchData();

   // Bind data to the buddy control
   BaseDataList baseDataListControl = null;
   ListControl listControl = null;
   if (_controlToPaginate is BaseDataList)
   {
    baseDataListControl = (BaseDataList) _controlToPaginate;
    baseDataListControl.DataSource = _dataSource;
    baseDataListControl.DataBind();
    return;
   }
   if (_controlToPaginate is ListControl)
   {
    listControl = (ListControl) _controlToPaginate;
    listControl.Items.Clear();
    listControl.DataSource = _dataSource;
    listControl.DataBind();
    return;
   }
  }
  private void FetchData()
  {
   SqlConnection cn=new SqlConnection(connectionString);
   SqlCommand cm=new SqlCommand();
   cm.Connection=cn;
   cm.Connection.Open();

   cm.CommandText="GetRecordFromPage";
   cm.CommandType=CommandType.StoredProcedure;
   cm.Parameters.Add("@tblName",SqlDbType.NVarChar,255);
   cm.Parameters.Add("@fldName",SqlDbType.NVarChar,255);
   cm.Parameters.Add("@PageSize",SqlDbType.Int);
   cm.Parameters.Add("@PageIndex",SqlDbType.Int);
   cm.Parameters.Add("@isCount",SqlDbType.Bit);
   cm.Parameters.Add("@OrderType",SqlDbType.Bit);
   cm.Parameters.Add("@strWhere",SqlDbType.NVarChar,1000);
   cm.Parameters["@tblName"].Value=tableName;
   cm.Parameters["@fldName"].Value=fieldName;
   cm.Parameters["@PageSize"].Value=pageSize;
   cm.Parameters["@PageIndex"].Value=pageIndex;
   cm.Parameters["@isCount"].Value=0;
   cm.Parameters["@OrderType"].Value=sortType;
   cm.Parameters["@strWhere"].Value=Where;

   SqlDataAdapter adapter = new SqlDataAdapter(cm);
   DataTable dtb = new DataTable();
   adapter.Fill(dtb);

   cm.Parameters["@isCount"].Value=isCount;
   recordCount=(int)cm.ExecuteScalar();
   pageCount=(int)Math.Ceiling((double)recordCount/pageSize);

   cm.Connection.Close();
   cm.Dispose();
   cn.Dispose();
   adapter.Dispose();

   // Configures the paged data source component
   if (_dataSource == null)
    _dataSource = new PagedDataSource();
   _dataSource.AllowCustomPaging = true;
   _dataSource.AllowPaging = true;
   _dataSource.CurrentPageIndex = 0;
   if(pageIndex==pageCount)
   {
    _dataSource.PageSize = (recordCount-(pageIndex-1)*pageSize);
   }
   else
   {
    _dataSource.PageSize = pageSize;
   }
   if(pageIndex==pageCount)
   {
    _dataSource.VirtualCount = (recordCount-(pageIndex-1)*pageSize);
   }
   else
   {
    _dataSource.VirtualCount = pageSize;
   }
   _dataSource.DataSource = dtb.DefaultView;
  }
  protected override void CreateChildControls()
  {
   Controls.Clear();
   if(!Page.IsPostBack)
   {
    ClearChildViewState();
   }

   //***********************************************
   Table table=new Table();
   table.Width=Unit.Percentage(100);
   table.CellPadding=0;
   table.CellSpacing=3;
   table.BorderWidth=0;
   table.Font.Size=FontUnit.Point(9);

   TableRow tr=new TableRow();

   TableCell tdInfo=new TableCell();
   tdInfo.Width=Unit.Percentage(25);
   tdInfo.HorizontalAlign=HorizontalAlign.Left;
   BuildInfo(tdInfo);
   tr.Cells.Add(tdInfo);

   TableCell tdNavigate=new TableCell();
   tdNavigate.Width=Unit.Percentage(50);
   tdNavigate.HorizontalAlign=HorizontalAlign.Center;
   BuildNavigator(tdNavigate);
   tr.Cells.Add(tdNavigate);

   TableCell tdGOTO=new TableCell();
   tdGOTO.Width=Unit.Percentage(25);
   tdGOTO.HorizontalAlign=HorizontalAlign.Right;
   BuildGOTO(tdGOTO);
   tr.Cells.Add(tdGOTO);

   table.Rows.Add(tr);
   Controls.Add(table);
  }
  private void BuildInfo(TableCell td)
  {
   LiteralControl lc=new LiteralControl();
   lc.Text="页码:"+pageIndex.ToString()+"|"+pageCount.ToString()+" 记录:"+((pageIndex-1)*pageSize+1)+"-"+((recordCount<pageSize)?recordCount:((pageIndex==pageCount)?recordCount:pageIndex*pageSize))+"|"+recordCount;
   td.Controls.Add(lc);
  }
  private void BuildNavigator(TableCell td)
  {
   int temp;
   if(pageIndex>showPageNumber)
   {
    LinkButton lbBack=new LinkButton();
    lbBack.CausesValidation=false;
    lbBack.Text="...";
    lbBack.CommandArgument="Back";
    lbBack.Command +=new CommandEventHandler(lb_Click);
    td.Controls.Add(lbBack);
    td.Controls.Add(new LiteralControl("&nbsp;"));
   }
   //*************************
   for(int i=0;i<showPageNumber;i++)
   {
    if((pageStart+i)<=pageCount)
    {
     temp=pageStart+i;
     LinkButton lbNumber=new LinkButton();
     lbNumber.CausesValidation=false;
     lbNumber.Text=temp.ToString();
     lbNumber.CommandArgument=temp.ToString();
     lbNumber.Command +=new CommandEventHandler(lbNumber_Click);
     td.Controls.Add(lbNumber);
     td.Controls.Add(new LiteralControl("&nbsp;"));
    }
   }
   if((pageCount-pageStart)>showPageNumber)
   {
    LinkButton lbForward=new LinkButton();
    lbForward.CausesValidation=false;
    lbForward.Text="...";
    lbForward.CommandArgument="Forward";
    lbForward.Command +=new CommandEventHandler(lb_Click);
    td.Controls.Add(lbForward);
   }
  }
  private void BuildGOTO(TableCell td)
  {
   TextBox tb=new TextBox();
   tb.ID="gotoPage";
   tb.BorderWidth=Unit.Pixel(1);
   tb.Width=Unit.Pixel(30);
   tb.EnableViewState=true;
   td.Controls.Add(tb);

   LiteralControl lc=new LiteralControl("&nbsp;");
   td.Controls.Add(lc);

   Button btn=new Button();
   btn.Text="GOTO";
   btn.CommandArgument=tb.ClientID;
   btn.Command +=new CommandEventHandler(lb_Click);
   td.Controls.Add(btn);

   RequiredFieldValidator val2=new RequiredFieldValidator();
   val2.ControlToValidate="gotoPage";
   val2.ErrorMessage="页码不能为空!";
   val2.Display=ValidatorDisplay.None;
   val2.ID="val2";
   td.Controls.Add(val2);

   RangeValidator val1=new RangeValidator();
   val1.Display=ValidatorDisplay.None;
   val1.ErrorMessage="无效的页码!";
   val1.ID="val1";
   val1.ControlToValidate="gotoPage";
   val1.Type=ValidationDataType.Integer;
   val1.MinimumValue="1";
   if(pageCount<1)
   {
    val1.MaximumValue="1";
   }
   else
   {
    val1.MaximumValue=pageCount.ToString();
   }
   
   td.Controls.Add(val1);

   ValidationSummary valAll=new ValidationSummary();
   valAll.ShowMessageBox=true;
   valAll.ShowSummary=false;
   td.Controls.Add(valAll);
  }
  private void lb_Click(Object Sender,CommandEventArgs e)
  {
   switch(e.CommandArgument.ToString())
   {
    case "Back":
     pageStart-=showPageNumber;
     pageIndex=pageStart;
     CreateChildControls();
     break;
    case "Forward":
     pageStart+=showPageNumber;
     pageIndex=pageStart;
     CreateChildControls();
     break;
    default:
     //TextBox tb=(TextBox)Parent.FindControl("CoolPager1:gotoPage");
        //pageIndex=Convert.ToInt32(tb.Text);
     string temp=Page.Request.Form[this.ClientID+":gotoPage"].ToString().Trim();
     try
     {
      pageIndex=Convert.ToInt32(temp);
      if(pageIndex % showPageNumber==0)
      {
       pageStart=pageIndex+1-showPageNumber;
      }
      else
      {
       pageStart=(int)Math.Floor((double)pageIndex/showPageNumber)*showPageNumber+1;
      }
      CreateChildControls();
     }
     catch
     {
     }
     break;
   }
   DataBind();
  }
  private void lbNumber_Click(Object Sender,CommandEventArgs e)
  {
   pageIndex=Convert.ToInt32(e.CommandArgument);
   DataBind();
  }
 }
}

0 0

相关博文

我的热门文章

img
取 消
img