您的位置:首页 > 其它

使用GridView控件分页显示数据

2017-02-14 22:26 525 查看
AllowPaging属性设置为true,表示允许分页,然后将PageSize设置为一个数字,表示每页来显示的记录数,最后在GridView控件中PageIndexChanging事件中设置PageIndex属性为当前页的索引值,并且重新绑定GridView控件,具体代码实现如下:

在  .aspx中 :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="4" OnPageIndexChanging="GridView1_PageIndexChanging" Width="515px">

        </asp:GridView>

    

    </div>

    </form>

</body>

</html>

在.cs中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridViewBind();
        }
    }

    public void GridViewBind()
    {
        //实例化SqlConnection 对象
        SqlConnection sqlCon = new SqlConnection();

        //实例化SqlConnection 对象连接数据库的字符串
        sqlCon.ConnectionString = @"server =XZ-201611211830\SQL2008;uid = sa;pwd = 123456;database =SchoolInformation";

        //定义SQL语句
        string SqlStr = "select * from tb_dept";

        //实例化SqlDataAdapter对象
        SqlDataAdapter da = new SqlDataAdapter(SqlStr,sqlCon);

        //实例化数据集DataSet
        DataSet ds = new DataSet();
        da.Fill(ds, "tb_dept");

        //绑定DataList控件
        GridView1.DataSource = ds;   //设置数据源,用于填充控件中项的值列表
        GridView1.DataBind();    //将控件及其所有子空间绑定到指定的数据源
        
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridViewBind();
    }


最后实现的界面标准;


 
点击 “2”之后显示:
 


 
备注:整体过程没有大问题,值得注意的是,是在 PageIndexChanging事件中设置PageIndex的属性,一开始我就搞错了,重新调整之后才能够实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐