无法删除GridView中的多个记录 [英] not able to delete multiple records in gridview

查看:50
本文介绍了无法删除GridView中的多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void btnDel_Click(object sender, EventArgs e)
   {

       try
       {
           con.ConnectionString = ConString;
           con.Open();
           foreach (GridViewRow row in grdvw.Rows)
           {
               //CheckBox cb = (CheckBox)row.FindControl("chkDel");
               CheckBox cb = (CheckBox)grdvw.Rows[row.RowIndex].FindControl("chkDel");
               if (cb.Checked)
               {
                   //int id =Convert.ToInt32( grdvw.DataKeys[row.RowIndex]["Emp_no"].ToString);
                   int Emp_no = Convert.ToInt32(grdvw.DataKeys[row.RowIndex].Values[0].ToString());

                   cmd = new SqlCommand("Delete from employee where Emp_no=" + Emp_no, con);
                   cmd.ExecuteNonQuery();
                   con.Close();
                   BindData();
                   lblMsg.Text = "Selected Records Deleted";

               }
           }

       }

       catch (Exception ex)
       {
           Response.Write(ex.Message);
       }

   }


我收到错误消息索引超出范围.必须为非负数,并且小于集合的大小.参数名称:index"
并且仅删除一条记录


I am getting an error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index "
and only single record is deleted

推荐答案

尝试以下操作:
Try this:
int Emp_no = Convert.ToInt32(grdvw.DataKeys[row.RowIndex].Value);


代替


Instead of

int Emp_no = Convert.ToInt32(grdvw.DataKeys[row.RowIndex].Values[0].ToString());



参考:
从datgridview和数据库访问中删除行 [ ^ ]



Refer:
Delete rows from datgridview and database access[^]



试试这个:
Hi,
Try this:
con.ConnectionString = ConString;
con.Open();
foreach (GridViewRow row in grdvw.Rows)
{
   //CheckBox cb = (CheckBox)row.FindControl("chkDel");
   CheckBox cb = (CheckBox)grdvw.Rows[row.RowIndex].FindControl("chkDel");
   if (cb.Checked)
   {
        int Emp_no = int.Parse(GridView1.DataKeys[row.RowIndex].Value.ToString());
        cmd = new SqlCommand("Delete from employee where Emp_no='" + Emp_no + "'", con);
        cmd.ExecuteNonQuery();
        //con.Close(); this should not come here.
        BindData();
        lblMsg.Text = "Selected Records Deleted";
    }
}
con.Close();



--Amit



--Amit


con.ConnectionString = ConString;
           con.Open();


您已在foreach循环之前打开连接,并且正在删除一条记录后关闭连接.

在同一foreach循环中打开连接


You have open the connnection before foreach loop and you are closing the connection after deleting one record.

Open the connection in same foreach loop


这篇关于无法删除GridView中的多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆