asp.net Girdview 批量删除错误的原因

本文介绍了一种解决在ASP.NET中使用GridView组件进行批量删除操作时出现的隔行删除问题的方法。通过先遍历所有选中的项并记录要删除的ID,然后再统一执行删除操作,避免了因页面刷新而导致的数据偏移问题。

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

foreach (GridViewRow gv in GridView3 .Rows)
        {
            CheckBox cBox = (CheckBox) gv.FindControl ("CheckBox1");
            if (cBox .Checked == true)
            {
                string type = Request. QueryString["type1" ].ToString();
                string id = GridView3. DataKeys[gv .RowIndex]. Value.ToString ();
                string sql = string. Format("delete from 用户表 where sn = '{0}'" , id);
                int num = Sqlhelper. ExecInsert_Update_Delete(sql );
                if (num != 0)
                {
                    string strsql = string. Format("Select * from 用户表  where 用户类型='{0}'" ,type);
                    DataTable dt = Sqlhelper. GetDataTable(strsql );
                    GridView3. DataSource = dt ;
                    GridView3. DataBind();
                }
                else
                {
                    //失败
                }
            }
        }


错误原因:每删完一行都会刷新页面,从而导致下一条要删除的数据已经往上移了,刷新完再去删除就找不到要删除的数据了,这就是导致删除的时候会隔行删除的原因.比如说我们要删除第1,2,3条数据,当删完第1条刷新页的时候,第2条数据往上移到第1条数据的位置了,第3条数据移到第2条的位置了,现在执行删除第2条数据的时候就会删到第3条,再想删除第3条的时候已经没有数据可删除,就会报错:


解决办法:全部删除完再刷新页面
        int num = 0;
        foreach (GridViewRow gv in GridView3 .Rows)
        {
            CheckBox cBox = (CheckBox) gv.FindControl ("CheckBox1");
            if (cBox .Checked == true)
            {
                string id = GridView3. DataKeys[gv .RowIndex]. Value.ToString ();
                string sql = string. Format("delete from 用户表  where sn = '{0}'" , id);
                num = Sqlhelper.ExecInsert_Update_Delete (sql);
            }
        }
        if (num != 0)
        {
            string type = Request.QueryString[ "type1"].ToString();
            string strsql = string. Format("Select * from 用户表  where 用户类型='{0}'" , type);
            DataTable dt = Sqlhelper. GetDataTable(strsql );
            GridView3. DataSource = dt ;
            GridView3. DataBind();
        }
        else
        {
            //失败
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值