分享
 
 
 

一个分页跟动态创建列的控件

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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("&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);

}

#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("&nbsp;");

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()+"]&nbsp;"+DataBinder.Eval(container.DataItem,"TITLE","<a href=\""+newsShowPage+"?NEWSID="+DataBinder.Eval(container.DataItem,"ID")+"\" target=\"_blank\">{0}</a>")+"&nbsp;&nbsp;"+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

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有