Private Sub DataGrid1_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.DeleteCommand
        Dim strid, strsql As Integer
        strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)
        strsql = "delete from enews1 where id='" + strid + "'"
        Dim sqlcon As New SqlConnection("SERVER=vabdna;uid=sa;pwd=yy;DATABASE=egov")
        sqlcon.Open()
        Dim sqlcommand As New SqlCommand
        sqlcommand.Connection = sqlcon
        sqlcommand.CommandText = strsql
        sqlcommand.ExecuteNonQuery()
        sqlcon.Close()
        sqlcon = Nothing
        sqlcommand = Nothing
        DataGrid1.EditItemIndex = -1
        BindToDataGrid()
    End Sub以上我写的程序段代码,用来实现删除数据库里的数据功能,但是当我点击“删除”按钮是,会报错如下:
异常详细信息: System.ArgumentOutOfRangeException: 索引超出范围。必须为非负值并小于集合大小。参数名: index不知何故,请高手们指点!!!谢!

解决方案 »

  1.   

    试一下把strsql = "delete from enews1 where id='" + strid + "'"里面的strid改成strid.Trim(),意思是去掉可能有的空格,试试
      

  2.   

    首先检查strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)是否取到值
    然后
    strsql = "delete from enews1 where id='" + strid + "'";
    数据库中的id是int的还是varchar的,如果是int就应该是这样写
    strsql = "delete from enews1 where id="+strid;
      

  3.   

    你试一试把
    strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)改成strid = Int32.Parse(DataGrid1.DataKeys.Item(e.Item.ItemIndex).ToString());我这是C#版的语言,不知道怎么改成你VB.NET版的,意思你应该可以明白,改改看
      

  4.   

    datagrid中的主键字段属性设置了没有
      

  5.   

    那确实有可能哦,要设置DataGrid1.DataKeyField="yourkeyfield"
      

  6.   

    改成:strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex+1)
      

  7.   

    我想问问datagrid中的主键字段属性如何设置?
    各位高手的修改方案我都试了,可是还是不行。报错为:
    异常详细信息: System.ArgumentOutOfRangeException: 索引超出范围。必须为非负值并小于集合大小。参数名: index总是说  strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)这一句有错。再次请教!!!!!!!
      

  8.   

    strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)
    这个思路有些问题?建议你逐语句调试,看看strid获取的什么数据?
    然后自然知道是什么错!
      

  9.   

    总是说  strid = DataGrid1.DataKeys.Item(e.Item.ItemIndex)这一句有错。
    ---------------------------
    取值好像不是这样取吧.应是
    strid = Ctype(DataGrid1.DataKeys(e.Item.ItemIndex),string)
    另外,要取键值,你就必须设置主键,设置方法,在datagrid绑定前
    me.datagrid1.DataKeyField = "主键字段名"
    me.datagrid1.DataBind()