Hi,

I am having problems inserting data to my database. This is the error I get when i click on the insert button:

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

Here is my code: The error is generated in this line:

If checkStudentOptions(GridView1.DataKeys(i).Value.ToString, uid) = 0 Then

Any help would be great. Thanks

Code:
Private Function checkStudentOptions(ByVal optionID As Int32, ByVal studentID As Int32) As Int32
        Dim dbconn As SqlConnection
        Dim sql As String
        Dim dbcomm As SqlCommand
        Dim dbread As Int32

        dbconn = New SqlConnection("Persist Security Info=True; User ID=sa; Password=password; Data Source=serverName; Initial Catalog=database")
        dbconn.Open()
        sql = "SELECT count(option_id) FROM pe_student_options WHERE option_id = " & optionID & " AND student_id=" & studentID
        dbcomm = New SqlCommand(sql, dbconn)
        dbread = dbcomm.ExecuteScalar
        dbconn.Close()
        Return dbread

    End Function
Code:
Protected Sub InsertSelectedOptions_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles InsertSelectedOptions.Click

        Dim i As Int16
        Dim dbconn As SqlConnection
        Dim sql As String
        Dim dbcomm As SqlCommand

        dbconn = New SqlConnection("Persist Security Info=True; User ID=sa; Password=password; Data Source=serverName; Initial Catalog=database")
        dbconn.Open()

        Dim uid As Int32
        Dim blnAdd As Boolean = False

        lblCheck.Text = "Can't add"

        For i = 0 To GridView1.Rows.Count - 1

            If CType(GridView1.Rows(i).FindControl("CheckBox1"), CheckBox).Checked() Then

                uid = getStudentID(Request.QueryString("student_id"))

                If checkStudentOptions(GridView1.DataKeys(i).Value.ToString, uid) = 0 Then
                    sql = "INSERT INTO [pe_student_options] ([option_id],student_id) VALUES (" & GridView1.DataKeys(i).Value.ToString & "," & uid & ")"
                    dbcomm = New SqlCommand(sql, dbconn)
                    dbcomm.ExecuteNonQuery()
                    blnAdd = True
                Else
                    If lblCheck.Text = "Can't add" Then
                        lblCheck.Text += " " & GridView1.Rows(i).Cells.Item(1).Text
                    Else
                        lblCheck.Text += ", " & GridView1.Rows(i).Cells.Item(1).Text
                    End If

                    lblCheck.ForeColor = Drawing.Color.Red
                End If

            End If

        Next
        If blnAdd = False Then
            lblCheck.Text += " - already exists"
        Else
            lblCheck.Text = String.Empty
        End If
        'GridView2.DataBind()
        dbconn.Close()
    End Sub