注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 Linux全攻略--文件和磁盘管理
 帮助

DataGrid分页(1)


2007-08-11 12:28:51
 标签:DataGrid   [推送到技术圈]

分页的一种方法:
       aspx页面:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>分页事例</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataGrid ID="DataGrid1" runat="server" AllowCustomPaging="True" AllowPaging="True"
            AutoGenerateColumns="False" Height="204px" OnPageIndexChanged="DataGrid1_PageIndexChanged"
            PageSize="5" Width="424px">
            <PagerStyle Mode="NumericPages" />
            <Columns>
                <asp:BoundColumn DataField="ProductID" HeaderText="ID"></asp:BoundColumn>
                <asp:BoundColumn DataField="Name"></asp:BoundColumn>
                <asp:BoundColumn DataField="Content"></asp:BoundColumn>
            </Columns>
        </asp:DataGrid></div>
    </form>
</body>
</html>
 后台aspx.cs代码:
 
public partial class page : System.Web.UI.Page
{
    int startIndex = 0;
    void Bind()//绑定数据方法
    {  //定义数据库连接对象
        SqlConnection cn = new SqlConnection("Data Source=Net33;Initial Catalog=QMSoftware;Integrated Security=True");
       //创建数据适配对象
       SqlDataAdapter da=new SqlDataAdapter("select ProductID ,Name ,Content from Product",cn);
       //创建DataSet对象
       DataSet ds=new DataSet();
       try
       {  //从指定的索引开始取PageSize条记录.
          da.Fill(ds,startIndex,DataGrid1.PageSize,"CurDataTable");
          da.Fill(ds,"AllDataTable");//填充数据集合
          //设置DataGrid控件实际要显示的项数
          DataGrid1.VirtualItemCount=ds.Tables["AllDataTable"].Rows.Count;
          //进行数据绑定
          DataGrid1.DataSource=ds.Tables["CurDataTable"];
          DataGrid1.DataBind();
       }
       catch
       {
            
           Page.RegisterClientScriptBlock("","<script>alert('数据显示错误');</script>");
           
       }
     }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        DataGrid1.CurrentPageIndex=e.NewPageIndex;
        //取得当前页为止总共有多少条记录,以便在下一页就从该记录开始读取
        startIndex=DataGrid1.PageSize*DataGrid1.CurrentPageIndex;
        //取得绑定数据
        Bind();
    }
}




    文章评论
 
 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: