Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Data Grid Delete - Error Index was out of range

Status
Not open for further replies.

DH

Programmer
Dec 8, 2000
168
I am trying to delete a record in a datagrid by clicking a delete link/button in the datagrid. I am receiving the following error when running the code below.

Error:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Code:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not (IsPostBack) Then
BindDataGrid("ID DESC")
End If
End Sub
Sub BindDataGrid(ByVal strSortField As String)
Dim cmdSelect As SqlCommand
cmdSelect = New SqlCommand("Select ID, dpurpose, tcontactname, person, timestamp From Quotes Order By " & strSortField, SqlConnection1)
SqlConnection1.Open()
DataGrid1.DataSource = cmdSelect.ExecuteReader()
DataGrid1.DataBind()
SqlConnection1.Close()
End Sub

Sub DataGrid1_SortCommand(ByVal s As Object, ByVal e As DataGridSortCommandEventArgs)
BindDataGrid(e.SortExpression)
End Sub
Sub MyDataGrid_DeleteCommand(ByVal s As Object, ByVal e As DataGridCommandEventArgs) Handles DataGrid1.DeleteCommand
Dim DeleteCmd As String = "DELETE from Quotes Where ID = @ID"
Dim Cmd As New SqlCommand(DeleteCmd, SqlConnection1)
Cmd.Parameters.Add(New SqlParameter("@ID", DataGrid1.DataKeys(e.Item.ItemIndex)))
SqlConnection1.Open()
Cmd.ExecuteNonQuery()
SqlConnection1.Close()
BindDataGrid("ID DESC")
End Sub
End Class

Can anyone offer any suggestions?

Thanks,

DH
 
Looks like the DataKeyField property of the grid is not set.
Code:
<asp:DataGrid id=myGrid DataKeyField="ID">
 
Thank you. That was it. Works perfect now.

DH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top