在网格视图行中删除

时间:2014-10-22 10:33:20

标签: asp.net sql-server c#-4.0 webforms

    protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
        con.Open();
        string query = "delete from details where sno='"+grd.DataKeys[e.RowIndex].Value+"'";-----(getting error like Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index)
        SqlCommand cmd = new SqlCommand(query,con);
        cmd.ExecuteNonQuery();
        filldata();
        con.Close();  
     }

像Index这样的错误超出了范围。必须是非负数且小于集合的大小

3 个答案:

答案 0 :(得分:1)

{

      SqlConnection con=newSqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
      con.Open();
      int Sno = Convert.ToInt32(grd.DataKeys[e.RowIndex].Values[0].ToString());
      string query="delete from Details where Sno="+Sno;
      SqlCommand cmd = new SqlCommand(query, con);
      int result = cmd.ExecuteNonQuery();
      con.Close();

}

答案 1 :(得分:0)

错误来自以下声明

grd.DataKeys[e.RowIndex]

并且意味着e.RowIndex的值超出了grd.DataKeys数组中元素的范围。

要进一步调试,您需要找出e.RowIndex的值,并查看grd.DataKeys数组中有多少元素。

答案 2 :(得分:0)

您应该在.aspx页面中为GridView添加DataKeyNames="your_id_column"属性

然后在grd_RowDeleting方法中,您可以grd.DataKeys[e.RowIndex].Valuegrd.DataKeys[e.RowIndex].Values["your_id_column"]

访问它

对字符串

也是更好的解析结果