关于DataGrid最后一页只有一行记录时,删除此记录出错的问题

一般在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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值