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

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

猜你喜欢

转载自blog.csdn.net/weixin_33901641/article/details/94688192