GridView使用DataBind方法绑定数据时的分页问题[转]

本文探讨了ASP.NET中GridView控件使用DataSource和DataBind进行数据绑定的方法,特别是在启用分页功能后,如何解决切换页面时出现的TheGridView'GridView1'firedeventPageIndexChangingwhichwasn'thandled.错误。提供了两种解决方案,包括修改EnableSortingAndPagingCallback属性和添加PageIndexChanging事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GridView支持DataSource和DataBind两种数据绑定方法,用DataBind时发现了些问题,总结一下。

首先在Design模式下生成一个Button和一个GridView,Button中的事件为:

1      protected   void  Button1_Click( object  sender, EventArgs e)
2 ExpandedBlockStart.gifContractedBlock.gif     {
3        Bind();
4    }

其中Bind()内容如下:

ContractedBlock.gif ExpandedBlockStart.gif Code
 1    public void Bind()
 2ExpandedBlockStart.gifContractedBlock.gif    {
 3        string strConn, strSQL;
 4        strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=Yes;";
 5        strSQL = "SELECT OrderID,CustomerID,EmployeeID,OrderDate FROM Orders WHERE OrderID<10300";
 6
 7        SqlDataAdapter da = new SqlDataAdapter(strSQL, strConn);
 8        DataSet ds = new DataSet();
 9        da.Fill(ds, "Orders");
10        GridView1.DataSource = ds;
11        GridView1.DataBind();
12    }


之前要导入一个namespace:

using  System.Data.SqlClient;

现在运行这个WEB,在页面上点击按钮Button,数据全部显示了出来,一切正常。现在将GridView的属性设置为允许分页,即:

AllowPaging = True


再次运行,GridView有了分页的效果,但当切换页面时,出现了如下错误:

"The GridView 'GridView1' fired event PageIndexChanging which wasn't handled. "

注意:此时GridView的EnableSortingAndPagingCallback属性为False。

解决方法:

方法一:
    1:将GridView的EnableSortingAndPagingCallback属性改成True;
    2:在Page_Load中重新绑定数据,即:

1 protected   void  Page_Load( object  sender, EventArgs e)
2 ExpandedBlockStart.gifContractedBlock.gif {
3    if (IsCallback)
4ExpandedSubBlockStart.gifContractedSubBlock.gif    {
5        Bind();
6    }

7}

方法二:
    1:保持GridView的EnableSortingAndPagingCallback属性不变,即:False;
    2:添加PageIndexChanging事件的内容,即:

1 protected   void  GridView1_PageIndexChanging( object  sender, GridViewPageEventArgs e)
2 ExpandedBlockStart.gifContractedBlock.gif {
3    GridView1.PageIndex = e.NewPageIndex;//更改当前页
4    Bind();
5}


两种方法,因EnableSortingAndPagingCallback的属性设置不同而不同,大家可根据实际需要自行选择。

转载于:https://www.cnblogs.com/qiangshu/archive/2009/10/29/1591841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值