ascx给DataGrid分页
这是我从网上摘下来的,但是找不着网址了,很遗憾。不知道还有用人跟我一样要用VS2003这个老掉牙的开发工具吗
这个控件也有不足,先把代码贴出来,缺点一会再说
代码
ascx前台
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="DataGridPad.ascx.cs" Inherits="CompanySystem.Controls.DataGridPad"
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="DataGridPad.ascx.cs" Inherits="CompanySystem.Controls.DataGridPad"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<asp:panel id="divPanel" HorizontalAlign="Right" Width="100%" Runat="server" Visible="False">
<INPUT style="WIDTH: 43px; HEIGHT:22px"id="hdRowCount" size="1" type="hidden" runat="server">
<INPUT style="WIDTH: 39px; HEIGHT: 22px" id="hdCurrentIndex" value="0" size="1" type="hidden"
runat="server">
<asp:Label id="LabelMsg" Runat="server"></asp:Label>
<asp:Button id="btnNavFirst" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="FIRST" Text="首页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavPrev" Runat="server"
Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="PREV" Text="上一页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavNext" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="NEXT" Text="下一页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavLast" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="LAST" Text="尾页" BorderStyle="Ridge"></asp:Button>
转到
<asp:TextBox id="tbPage" Width="31px" Runat="server"></asp:TextBox>
<asp:Label id="LabelMsg2" Runat="server">页</asp:Label>
<asp:Button id="btnNavGo" Runat="server" CausesValidation="False" BorderWidth="1px" CommandName="GO" Text="确定" BorderStyle="Ridge"></asp:Button>
</asp:panel>
<asp:panel id="divPanel" HorizontalAlign="Right" Width="100%" Runat="server" Visible="False">
<INPUT style="WIDTH: 43px; HEIGHT:22px"id="hdRowCount" size="1" type="hidden" runat="server">
<INPUT style="WIDTH: 39px; HEIGHT: 22px" id="hdCurrentIndex" value="0" size="1" type="hidden"
runat="server">
<asp:Label id="LabelMsg" Runat="server"></asp:Label>
<asp:Button id="btnNavFirst" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="FIRST" Text="首页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavPrev" Runat="server"
Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="PREV" Text="上一页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavNext" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="NEXT" Text="下一页" BorderStyle="Ridge"></asp:Button>
<asp:Button id="btnNavLast" Runat="server" Font-Size="XX-Small" CausesValidation="False" BorderWidth="1px" CommandName="LAST" Text="尾页" BorderStyle="Ridge"></asp:Button>
转到
<asp:TextBox id="tbPage" Width="31px" Runat="server"></asp:TextBox>
<asp:Label id="LabelMsg2" Runat="server">页</asp:Label>
<asp:Button id="btnNavGo" Runat="server" CausesValidation="False" BorderWidth="1px" CommandName="GO" Text="确定" BorderStyle="Ridge"></asp:Button>
</asp:panel>
代码
ascx后台
namespace CompanySystem.Controls
{
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
/// <summary>
/// DataGridPad 的摘要说明。
/// </summary>
///
public delegate void BindDataDelegate();
public delegate void BindCustomDataDelegate(int currentPage);
public abstract class DataGridPad : System.Web.UI.UserControl
{
public BindDataDelegate BindData1;
public BindCustomDataDelegate BindData2;
protected System.Web.UI.WebControls.Label LabelMsg;
protected System.Web.UI.WebControls.Button btnNavFirst;
protected System.Web.UI.WebControls.Panel divPanel; //每页显示行数
protected System.Web.UI.HtmlControls.HtmlInputHidden hdRowCount; //数据总数
protected System.Web.UI.WebControls.Button btnNavPrev;
protected System.Web.UI.WebControls.Button btnNavNext;
protected System.Web.UI.WebControls.Button btnNavLast;
protected System.Web.UI.WebControls.TextBox tbPage;
protected System.Web.UI.WebControls.Label LabelMsg2;
protected System.Web.UI.WebControls.Button btnNavGo;
protected System.Web.UI.HtmlControls.HtmlInputHidden hdCurrentIndex; //当前页
#region 参数
private DataGrid dg;
private bool autohidden=true; //自动隐藏
private int pagesize=10; //缺省分页
private int itemCount=0;
private int dispStyle=1;
enum DataPageType {AllData,PageData}; //数据分页类别,提取所有数据或者提取当前页数据
private DataPageType curDataPageType; //当前数据分页类别
public DataGrid Target
{
get{return dg;}
set{dg=value;}
}
public bool AutoHidden
{
get{return autohidden;}
set{autohidden=value;}
}
public int PageSize
{
get{return pagesize;}
set{pagesize=value;}
}
public int ItemCount
{
get{return int.Parse(this.hdRowCount.Value);}
set{itemCount=value;hdRowCount.Value=value.ToString();}
}
#endregion
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
/// <summary>
/// 导航按钮点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NavigationButtonClick(object sender,EventArgs e)
{
string direction=((Button)sender).CommandName;
int currentPageIndex,pageCount;
currentPageIndex=int.Parse(this.hdCurrentIndex.Value);
pageCount=this.ItemCount/dg.PageSize+1;
//根据按键的不同,到达不同的页
switch(direction.ToUpper())
{
case "FIRST":
currentPageIndex=0;
break;
case "PREV":
currentPageIndex=Math.Max(currentPageIndex-1,0);
break;
case "NEXT":
currentPageIndex=Math.Min(currentPageIndex+1,pageCount-1);
break;
case "LAST":
currentPageIndex=Math.Max(pageCount-1,0);
break;
case "GO":
try
{
currentPageIndex=Math.Min(pageCount-1,int.Parse(this.tbPage.Text)-1);
this.tbPage.Text="";
}
catch
{
this.tbPage.Text="";
}
break;
default:
break;
}
if(curDataPageType==DataPageType.AllData)
dg.CurrentPageIndex= currentPageIndex;
this.hdCurrentIndex.Value=currentPageIndex.ToString();
if(BindData1 != null)
BindData1();
if(BindData2 != null)
BindData2(currentPageIndex);
}
/// <summary>
/// DataGrid绑定前,设置导航条
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void zxDataBinding(object sender,EventArgs e)
{
int newCount=0;
int PageCount =0;
int currentPageIndex = int.Parse(this.hdCurrentIndex.Value);
if(dg.DataSource==null)
{
SetButtonState(0);
return;
}
//如果是分页数据,直接取总记录数,否则,从数据源取得
if(curDataPageType == DataPageType.PageData)
{
newCount=this.ItemCount;
}
else
{
if(dg.DataSource.GetType().ToString().ToLower()=="system.data.datatable")
{
newCount=((DataTable)dg.DataSource).Rows.Count;
}
else if(dg.DataSource.GetType().ToString().ToLower()=="system.data.dataview")
{
newCount=((DataView)dg.DataSource).Count;
}
else if(dg.DataSource.GetType().ToString().ToLower()=="system.data.dataset")
{
newCount=((DataSet)dg.DataSource).Tables[0].Rows.Count;
}
else if(dg.DataSource.GetType().ToString().ToLower()=="system.collections.ilist")
{
newCount = ((IList)dg.DataSource).Count;
}
this.hdRowCount.Value=newCount.ToString();
}
//数据邦定时判断,当前页是否越界
if(newCount>0)
{
PageCount=(int)((newCount-1)/pagesize+1);
if(currentPageIndex>PageCount-1)
{
currentPageIndex = PageCount-1;
}
}
else
{
PageCount=0;
currentPageIndex=0;
}
//显示风格
switch(dispStyle)
{
case 1:
this.LabelMsg.Text="共"+PageCount.ToString()+"页 第"+(currentPageIndex+1).ToString()+"页";
this.LabelMsg.Text+=" 总记录数:"+newCount.ToString()+"";
break;
case 2:
this.LabelMsg.Text=(currentPageIndex+1).ToString()+"/"+PageCount.ToString()+"页";
this.LabelMsg.Text+="总数:"+newCount.ToString();
break;
}
//是否自动隐藏
if(autohidden)
{
this.divPanel.Visible=((newCount-1)/pagesize>0);
}
else
{
this.divPanel.Visible=true;
}
SetButtonState(PageCount);
if(curDataPageType == DataPageType.AllData)
{
dg.CurrentPageIndex=currentPageIndex;
}
this.hdCurrentIndex.Value=currentPageIndex.ToString();
}
/// <summary>
/// //设置导航按钮是否可用的状态
/// </summary>
/// <param name="pageCount">总页数</param>
private void SetButtonState(int pageCount)
{
int currentPageIndex;
currentPageIndex=int.Parse(this.hdCurrentIndex.Value);
btnNavFirst.Enabled=(currentPageIndex>0);
btnNavPrev.Enabled=(currentPageIndex>0);
btnNavNext.Enabled=(currentPageIndex<pageCount-1);
btnNavLast.Enabled=(currentPageIndex<pageCount-1);
}
/// <summary>
/// 获取原子SQL会返回的结果行总数
/// </summary>
/// <param name="unitSql">原sql</param>
/// <returns>目标sql</returns>
public string GetCountSql(string unitSql)
{
string sql;
sql="select count(*) from ("+unitSql+") CountTable";
return sql;
}
/// <summary>
/// 获取用于分页的sql语句
/// </summary>
/// <param name="unitSql">原sql</param>
/// <param name="keyField">关键列</param>
/// <param name="currentPage">要显示的页面编号</param>
/// <param name="pageSize">每页显示记录数</param>
/// <returns></returns>
public string GetPageingSql(string unitSql,string keyField,int currentPage,int pageSize)
{
string sql;
sql="select * from (select top "+pageSize.ToString() +" * from (select top "+(currentPage+1)*pageSize+
" * from ( "+unitSql+" ) PageingTable1 order by "+keyField+" ) PageingTable2 order by "+
keyField.Replace(","," desc ,")+" desc )PageingTable3 order by "+keyField;
return sql;
}
/// <summary>
/// 设置导航对象的目标DataGrid以及针对DataGrid的数据邦定事件
/// </summary>
/// <param name="dg">DataGrid对象</param>
/// <param name="aBindData1">数据绑定事件</param>
public void SetTarget(DataGrid dg,BindCustomDataDelegate aBindData1)
{
curDataPageType=DataPageType.PageData;
BindData2=aBindData1;
BindEvent(dg);
}
public void SetTarget(DataGrid dg,BindDataDelegate aBindData1)
{
curDataPageType=DataPageType.AllData;
BindData1=aBindData1;
BindEvent(dg);
}
private void BindEvent(DataGrid dgd)
{
dg=dgd;
//绑定事件
btnNavFirst.Click+=new EventHandler(this.NavigationButtonClick);
btnNavNext.Click+=new EventHandler(this.NavigationButtonClick);
btnNavPrev.Click+=new EventHandler(this.NavigationButtonClick);
btnNavLast.Click+=new EventHandler(this.NavigationButtonClick);
btnNavGo.Click+=new EventHandler(this.NavigationButtonClick);
dg.DataBinding+=new EventHandler(this.zxDataBinding);
}
/// <summary>
/// 设置DataGrid样式
/// </summary>
/// <param name="aPageSize">每页显示行数</param>
/// <param name="aAutoHidden">是否自动隐藏</param>
/// <param name="aDispStyle">显示风格,1:标准 2:简约</param>
public void SetStyle(int aPageSize,bool aAutoHidden,int aDispStyle)
{
pagesize=aPageSize;
autohidden=aAutoHidden;
dispStyle=aDispStyle;
this.divPanel.Visible=!aAutoHidden;
dg.AllowPaging=true;
dg.AllowCustomPaging=false;
dg.PagerStyle.Visible=false;
dg.PageSize=pagesize;
dg.PagerStyle.Mode=PagerMode.NumericPages;
dg.PagerStyle.HorizontalAlign=HorizontalAlign.Right;
}
public void SetStyle(int aPageSize,bool aAutoHidden)
{
SetStyle(aPageSize,aAutoHidden,1);
}
public void SetStyle(int aPageSize)
{
SetStyle(aPageSize,true);
}
}
}在aspx里:代码<table border="0" cellSpacing="0" cellPadding="0" width="100%" align="center">
<tr>
<td width="100%"><asp:datagrid id="projectdg" runat="server" Width="100%" ItemStyle-Font-Size="12px" AutoGenerateColumns="False">
<Columns>
<asp:ButtonColumn HeaderText="ID" DataTextField="ProjectID" CommandName="edit"></asp:ButtonColumn>
<asp:ButtonColumn DataTextField="ProjectName" HeaderText="名称" HeaderStyle-Font-Size="13px" CommandName="edit"></asp:ButtonColumn>
<asp:BoundColumn DataField="UpIndustry" HeaderText="上游行业" HeaderStyle-Font-Size="13px"></asp:BoundColumn>
<asp:BoundColumn DataField="DownIndustry" HeaderText="下游行业" HeaderStyle-Font-Size="13px"></asp:BoundColumn>
<asp:BoundColumn DataField="SpecialPolicies" HeaderText="适用特殊政策" HeaderStyle-Font-Size="13px"></asp:BoundColumn>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox Runat="server" ID="chkAll">删除</asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox Runat="server" ID="chkItem"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid></td>
</tr>
<tr>
<td><uc1:datagridpad id="DataGridPad1" runat="server"></uc1:datagridpad></td>
</tr>
</table>在aspx.cs里这么调用
代码using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BLL;
using Test.Controls; //我的ascx控件放在Test项目的Controls文件夹下
using System.Web.Caching;
namespace Test.Show
{
/// <summary>
/// CompanyShow 的摘要说明。
/// </summary>
public class ProjectShow : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid projectdg;
protected DataGridPad DataGridPad1; //注意这里,一定要有,手动添加的
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindDG();
}
//分页样式
this.DataGridPad1.SetTarget(this.companydg,new BindDataDelegate(BindDG));
this.DataGridPad1.SetStyle(10,true);
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void BindDG()
{
MyProject project=new MyProject();
IList list=project.GetProjects();
this.projectdg.DataSource=list;
this.projectdg.DataBind();
}
贴完了,它的缺点是AutoPostBack不能使用了,并且如果我的DataGrid第一行是链接列(如我贴出的DataGrid),点击的时候,却不会跳转,而且还会在DataGrid的最后一行生产一个空白行。其他行或列不会出现这个问题