【问题标题】:In grid view row deleting在网格视图中删除行
【发布时间】:2014-12-17 18:54:38
【问题描述】:
    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();  
     }

gettnig 错误,例如 Index 超出范围。必须是非负数且小于集合的大小

【问题讨论】:

  • 你有什么问题?

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


【解决方案1】:

错误来自以下语句

grd.DataKeys[e.RowIndex]

并且表示e.RowIndex 的值超出了grd.DataKeys 数组的元素范围。

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

【讨论】:

    【解决方案2】:

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

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

    另外最好将结果解析为字符串

    【讨论】:

      【解决方案3】:

      {

            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();
      

      }

      【讨论】:

      • 我不得不使用 Grid1.Rows[Grid1.SelectedIndex].Cells[1].Text 让它为我工作。但你的帖子确实为我指明了正确的方向
      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多