一个分页跟动态创建列的控件
using System;
using System.Web;
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 Yeno
{
/// <summary>
/// coolPager 的摘要说明。
/// </summary>
#region 构造枚举类型
public enum SortType
{
ASC=0,Desc=1
};
public enum IsCount
{
noReturnRecordCount=0,returnRecordCount
};
public enum ManageSwitch
{
ON=0,OFF
};
#endregion
[DefaultProperty(""),
ToolboxData("<{0}:EINews runat=server></{0}:EINews>")]
public class EINews : System.Web.UI.WebControls.WebControl,INamingContainer
{
protected int recordCount=0;
protected Control _controlToPaginate;
protected PagedDataSource _dataSource;
protected Repeater _rp=new Repeater();
protected string _connectionString="",_tableName="";
#region 属性
[Bindable(true),
Category("控件专有属性"),
Description("数据源连接字符串"),
DefaultValue("")]
public string connectionString
{
get
{
return _connectionString;
}
set
{
_connectionString=value;
}
}
//表名
[Category("控件专有属性"),Description("查询表名"),DefaultValue("")]
public string tableName
{
get
{
return _tableName;
}
set
{
_tableName=value;
}
}
//排序字段名
[Category("控件专有属性"),Description("排序字段"),DefaultValue("")]
public string fieldName
{
get
{
Object obj=ViewState["fieldName"];
return (obj==null)?String.Empty:obj.ToString();
}
set
{
ViewState["fieldName"]=value;
}
}
//每页显示记录数
[Category("控件专有属性"),Description("每页记录数"),DefaultValue("")]
public int pageSize
{
get
{
Object obj=ViewState["pageSize"];
return (obj==null)?15:Convert.ToInt32(obj);
}
set
{
ViewState["pageSize"]=value;
}
}
//页码
[Category("控件专有属性"),Description("当前页码"),DefaultValue(""),Browsable(false)]
public int pageIndex
{
get
{
Object obj=ViewState["pageIndex"];
return (obj==null)?1:Convert.ToInt32(obj);
}
set
{
ViewState["pageIndex"]=value;
}
}
//是否返回记录总数
[Category("控件专有属性"),Description("是否返回记录总数"),DefaultValue(""),Browsable(false)]
public IsCount isCount
{
get
{
return IsCount.returnRecordCount;
}
}
//排序类型
[Category("控件专有属性"),Description("排序类型"),DefaultValue("")]
public SortType sortType
{
get
{
Object obj=ViewState["sortType"];
return (obj==null)?SortType.ASC:(SortType)obj;
}
set
{
ViewState["sortType"]=value;
}
}
[Category("控件专有属性"),Description("显示导航数字数"),DefaultValue("")]
public int showPageNumber
{
get
{
Object obj=ViewState["showPageNumber"];
return (obj==null)?10:Convert.ToInt32(obj);
}
set
{
ViewState["showPageNumber"]=value;
}
}
[Category("控件专有属性"),Description("开始页"),DefaultValue(""),Browsable(false)]
public int pageStart
{
get
{
Object obj=ViewState["pageStart"];
return (obj==null)?1:Convert.ToInt32(obj);
}
set
{
ViewState["pageStart"]=value;
}
}
[Category("控件专有属性"),Description("总页数,自动生成"),DefaultValue(""),Browsable(false)]
public int pageCount
{
get
{
Object obj=ViewState["pageCount"];
return (obj==null)?1:Convert.ToInt32(obj);
}
set
{
ViewState["pageCount"]=value;
}
}
[Category("控件专有属性"),Description("类型"),DefaultValue("")]
public string newsType
{
set
{
ViewState["newsType"]=value;
}
get
{
Object obj=ViewState["newsType"];
return (obj==null)?String.Empty:obj.ToString();
}
}
[Category("控件专有属性"),Description("表格CSS"),DefaultValue("")]
public string tableCSS
{
set
{
ViewState["tableCSS"]=value;
}
get
{
Object obj=ViewState["tableCSS"];
return (obj==null)?String.Empty:obj.ToString();
}
}
[Category("控件专有属性"),Description("AlternateCSS"),DefaultValue("")]
public string alternateCSS
{
set
{
ViewState["alternateCSS"]=value;
}
get
{
Object obj=ViewState["alternateCSS"];
return (obj==null)?String.Empty:obj.ToString();
}
}
[Category("控件专有属性"),Description("itemCSS"),DefaultValue("")]
public string itemCSS
{
set
{
ViewState["itemCSS"]=value;
}
get
{
Object obj=ViewState["itemCSS"];
return (obj==null)?String.Empty:obj.ToString();
}
}
[Category("控件专有属性"),Description("buttonCSS"),DefaultValue("")]
public string buttonCSS
{
set
{
ViewState["buttonCSS"]=value;
}
get
{
Object obj=ViewState["buttonCSS"];
return (obj==null)?String.Empty:obj.ToString();
}
}
[Category("控件专有属性"),Description("textboxCSS"),DefaultValue("")]
public string textboxCSS
{
set
{
ViewState["textboxCSS"]=value;
}
get
{
Object obj=ViewState["textboxCSS"];
return (obj==null)?String.Empty:obj.ToString();
}
}
//Where子句
[Category("控件专有属性"),Description("where子句,不带where"),DefaultValue("")]
public string Where
{
get
{
Object obj=ViewState["Where"];
string NewsType="TYPE like '%"+newsType+"%'";
return (obj==null)?NewsType:NewsType+" and "+obj.ToString();
}
set
{
ViewState["Where"]=value;
}
}
[Category("控件专有属性"),Description("新闻显示页面名称!")]
public string newsShowPage
{
get
{
Object obj=ViewState["newsShowPage"];
return (obj==null)?String.Empty:obj.ToString();
}
set
{
ViewState["newsShowPage"]=value;
}
}
[Category("控件专有属性"),Description("是否开放管理功能!")]
public ManageSwitch manageSwitch
{
get
{
Object obj=ViewState["manageSwitch"];
return (obj==null)?ManageSwitch.OFF:(ManageSwitch)obj;
}
set
{
ViewState["manageSwitch"]=value;
}
}
[Category("控件专有属性"),Description("编辑页文件名!")]
public string editPage
{
get
{
Object obj=ViewState["editPage"];
return (obj==null)?String.Empty:obj.ToString();
}
set
{
ViewState["editPage"]=value;
}
}
[Category("控件专有属性"),Description("删除页文件名!")]
public string deletePage
{
get
{
Object obj=ViewState["deletePage"];
return (obj==null)?String.Empty:obj.ToString();
}
set
{
ViewState["deletePage"]=value;
}
}
#endregion
/// <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)
CreateChildControls();
//DataBind();
base.Render(output);
}
public override void DataBind()
{
base.DataBind();
ChildControlsCreated = false;
if (connectionString == "" || tableName == "")
return;
// Fetch data
FetchData();
// Bind data to the buddy control
_rp.DataSource = _dataSource;
_rp.DataBind();
return;
}
private void ErrorShow(string errorMessage)
{
HttpContext.Current.Response.Write("<script language=javascript>window.alert(\""+errorMessage+"\");</script>");
}
private void FetchData()
{
#region
SqlConnection cn=new SqlConnection();
SqlCommand cm=new SqlCommand();
cm.Connection=cn;
SqlDataAdapter adapter=new SqlDataAdapter();
try
{
cn.ConnectionString=connectionString;
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;
adapter.SelectCommand=cm;
DataTable dtb = new DataTable();
adapter.Fill(dtb);
cm.Parameters["@isCount"].Value=isCount;
recordCount=(int)cm.ExecuteScalar();
pageCount=(int)Math.Ceiling((double)recordCount/pageSize);
// 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;
}
catch
{
ErrorShow("从数据库取得数据时发生错误!");
}
finally
{
cm.Connection.Close();
cm.Dispose();
cn.Dispose();
adapter.Dispose();
}
#endregion
}
protected override void CreateChildControls()
{
#region
try
{
Controls.Clear();
if(!Page.IsPostBack)
{
ClearChildViewState();
}
//***********************************************
Table table1=new Table();
table1.Width=Unit.Percentage(100);
table1.Height=Unit.Percentage(100);
TableRow tr1=new TableRow();
TableCell td1=new TableCell();
td1.VerticalAlign=VerticalAlign.Top;
td1.Height=Unit.Percentage(100);
_rp.HeaderTemplate=new MyTemplate(ListItemType.Header,tableCSS,alternateCSS,itemCSS,newsShowPage,manageSwitch,editPage,deletePage);
_rp.ItemTemplate=new MyTemplate(ListItemType.Item,tableCSS,alternateCSS,itemCSS,newsShowPage,manageSwitch,editPage,deletePage);
_rp.AlternatingItemTemplate=new MyTemplate(ListItemType.AlternatingItem,tableCSS,alternateCSS,itemCSS,newsShowPage,manageSwitch,editPage,deletePage);
_rp.FooterTemplate=new MyTemplate(ListItemType.Footer,tableCSS,alternateCSS,itemCSS,newsShowPage,manageSwitch,editPage,deletePage);
_rp.ID="SHOW";
//Controls.Add(_rp);
td1.Controls.Add(_rp);
tr1.Cells.Add(td1);
table1.Rows.Add(tr1);
TableRow tr2=new TableRow();
TableCell td2=new TableCell();
td2.VerticalAlign=VerticalAlign.Bottom;
Table table=new Table();
table.Width=Unit.Percentage(100);
table.CellPadding=0;
table.CellSpacing=3;
table.BorderWidth=0;
table.Font.Size=FontUnit.Point(10);
TableRow tr=new TableRow();
TableCell tdInfo=new TableCell();
tdInfo.Width=Unit.Percentage(30);
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(20);
tdGOTO.HorizontalAlign=HorizontalAlign.Right;
BuildGOTO(tdGOTO);
tr.Cells.Add(tdGOTO);
table.Rows.Add(tr);
td2.Controls.Add(table);
tr2.Cells.Add(td2);
table1.Rows.Add(tr2);
Controls.Add(table1);
//Controls.Add(table);
DataBind();
}
catch(Exception ex)
{
ErrorShow("创建子控件时发生错误:"+ex.Message);
}
#endregion
}
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)
{
#region
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(" "));
}
//*************************
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(" "));
}
}
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);
}
#endregion
}
private void BuildGOTO(TableCell td)
{
#region
TextBox tb=new TextBox();
tb.ID="gotoPage";
tb.BorderWidth=Unit.Pixel(1);
tb.Width=Unit.Pixel(30);
tb.CssClass=textboxCSS;
tb.EnableViewState=true;
td.Controls.Add(tb);
LiteralControl lc=new LiteralControl(" ");
td.Controls.Add(lc);
Button btn=new Button();
btn.Text="GOTO";
btn.CssClass=buttonCSS;
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);
#endregion
}
private void lb_Click(Object Sender,CommandEventArgs e)
{
#region
switch(e.CommandArgument.ToString())
{
case "Back":
pageStart-=showPageNumber;
pageIndex=pageStart;
CreateChildControls();
break;
case "Forward":
pageStart+=showPageNumber;
pageIndex=pageStart;
CreateChildControls();
break;
default:
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
{
ErrorShow("翻页时发生错误!");
}
break;
}
DataBind();
#endregion
}
private void lbNumber_Click(Object Sender,CommandEventArgs e)
{
pageIndex=Convert.ToInt32(e.CommandArgument);
DataBind();
}
}
public class MyTemplate : ITemplate
{
#region
ListItemType templateType;
string tableCSS="";
string alternateCSS="";
string itemCSS="";
string newsShowPage="";
string editPage="";
string deletePage="";
ManageSwitch _manageSwitch;
public MyTemplate(ListItemType type)
{
templateType = type;
}
public MyTemplate(ListItemType type,string TableCSS,string AlternateCSS,string ItemCSS,string NewsShowPage,ManageSwitch manageSwitch,string EditPage,string DeletePage)
{
templateType = type;
tableCSS=TableCSS;
alternateCSS=AlternateCSS;
itemCSS=ItemCSS;
newsShowPage=NewsShowPage;
_manageSwitch=manageSwitch;
editPage=EditPage;
deletePage=DeletePage;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
switch(templateType)
{
case ListItemType.Header:
lc.Text="<TABLE CellSpacing=\"0\" CellPadding=\"5\" CLASS=\""+tableCSS+"\">";
break;
case ListItemType.Item:
lc.Text="<TR><TD CLASS=\""+itemCSS+"\">";
lc.DataBinding += new EventHandler(TemplateControl_DataBinding);
break;
case ListItemType.AlternatingItem:
lc.Text = "<TR><TD CLASS=\""+alternateCSS+"\">";
lc.DataBinding += new EventHandler(TemplateControl_DataBinding);
break;;
case ListItemType.Footer:
lc.Text = "</TABLE>";
break;
}
container.Controls.Add(lc);
}
private void TemplateControl_DataBinding(object sender,System.EventArgs e)
{
string css="";
Literal lc;
lc = (Literal) sender;
RepeaterItem container = (RepeaterItem) lc.NamingContainer;
lc.Text += "["+Convert.ToString(DataBinder.Eval(container.DataItem,"PREFIX")).Trim()+"] "+DataBinder.Eval(container.DataItem,"TITLE","<a href=\""+newsShowPage+"?NEWSID="+DataBinder.Eval(container.DataItem,"ID")+"\" target=\"_blank\">{0}</a>")+" "+DataBinder.Eval(container.DataItem,"PUB_TIME","{0:yyyy-M-d}");
lc.Text+="</TD>";
if(_manageSwitch==ManageSwitch.ON)
{
switch(templateType)
{
case ListItemType.Item:
css=itemCSS;
break;
case ListItemType.AlternatingItem:
css=alternateCSS;
break;;
}
lc.Text+="<TD CLASS=\""+css+"\"><a href=\""+editPage+"?NEWSID="+DataBinder.Eval(container.DataItem,"ID")+"\" target=\"_blank\">编辑</a></TD>";
lc.Text+="<TD CLASS=\""+css+"\"><a href=\""+deletePage+"?NEWSID="+DataBinder.Eval(container.DataItem,"ID")+"\" target=\"_blank\">删除</a></TD>";
}
lc.Text+="</TR>";
}
#endregion
}
}