从gridview中删除多行时获取错误 [英] Getting error while deleting Multiple rows from gridview

查看:86
本文介绍了从gridview中删除多行时获取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.<br />
<br />



当我删除单个时使用复选框按钮单击然后它工作正常但是当我删除多行时它会抛出异常。



任何人都可以帮助我吗?



这是我的代码 -




When i''m deleting single row using checkbox on button click then it is working fine but when i''m deleting multiple row then it is throwing exception.

can anyone help me out?

here is my code-

foreach (GridViewRow row in GridView1.Rows)
        {

            CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
            if (chk.Checked)
            {

                int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                SqlConnection sqlconn = new SqlConnection("server=.\\sqlexpress;database=practice;integrated security=true");
                SqlCommand sqlcomm = new SqlCommand("delete from prac where id='"+id+"'", sqlconn);
                sqlconn.Open();
                sqlcomm.ExecuteNonQuery();
                sqlconn.Close();
                Label1.Text = "Record Deleted";
                Binddata();
            
            }
        
        
        }

推荐答案

你的问题是那个你在一行的每次迭代中调用Binddata()。

完全移出Binddata()调用foreach。在完成处理之前,不要重新绑定数据。

Your issue is that you call Binddata() on every iteration of a row.
Move the Binddata() call out of the foreach completely. Don''t rebind your data until you are done processing.
foreach (GridViewRow row in GridView1.Rows)
{
   CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
   if (chk.Checked)
   {
      int id = Convert.ToInt32("",GridView1.DataKeys[row.RowIndex].Value);
      SqlConnection sqlconn = new SqlConnection("server=.\\sqlexpress;database=practice;integrated security=true");
      SqlCommand sqlcomm = new SqlCommand("delete from prac where id='"+id+"'", sqlconn);
      sqlconn.Open();
      sqlcomm.ExecuteNonQuery();
      sqlconn.Close();
      Label1.Text = "Record Deleted";           
   }    
}
Binddata();


这篇关于从gridview中删除多行时获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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