一般在DataGrid中使用删除功能的时候,我们有时可能会遇到这样的情况:当我们执行一般的删除时可以正常删除,但是当最后一页只有一行记录时,这时我们删除此记录会出现下面的错误提示:
Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount.
aa这是因为当我们删除后,DataGrid的总页数(PageCount)减少了,但是当前页的索引(CurrentPageIndex)还是以前的值,这样就出现了上面的异常。
解决方法:
我们可以不需要修改一些事件的代码,可以在绑定数据的时候,判断一下当前页的索引:
private void GetData()
{
    
    SqlConnection cn = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
    string str = "select * from Table1";
    SqlDataAdapter da = new SqlDataAdapter(str, cn);
    DataSet ds = new DataSet();
    da.Fill(ds);
    this.DataGrid1.DataSource = ds;
    this.DataGrid1.DataKeyField = "id";
    try
    {
        this.DataGrid1.DataBind();
    }
    catch
    {
        //判断当前页的索引是否正确
        if(DataGrid1.CurrentPageIndex < 0 || DataGrid1.CurrentPageIndex>=DataGrid1.PageCount)
        {
            DataGrid1.CurrentPageIndex = DataGrid1.CurrentPageIndex -1;
        }
        this.DataGrid1.DataBind();
    }
}
posted on 2006-04-28 12:58  记得忘记  阅读(594)  评论(0编辑  收藏  举报