tpe的一个未处理的例外' System.ArgumentOutOfRangeException'发生在mscorlib.dll中

时间:2016-01-24 11:31:13

标签: vb.net datagridview unhandled-exception

未处理的类型' System.ArgumentOutOfRangeException'发生在mscorlib.dll

其他信息:指数超出范围。必须是非负数且小于集合的大小。

上面未处理的异常显示我在代码下运行时:

Private Sub chUser()
    conn = New SqlConnection(conStr)
    conn.Open()
    myConn.clName = clNameDGV.SelectedRows.Item(0).Cells(0).Value //EXCEPTION SHOWS FOR THIS LINE
    Dim comStr As String = "Select Count(*) from Login_Detail Where Clinic_Name = '" & clNameDGV.SelectedRows.Item(0).Cells(0).Value & "'"
    Dim comm As New SqlCommand(comStr, conn)
    Dim i As Integer = comm.ExecuteScalar()
    If i = 0 Then
        If MessageBox.Show("No User Information found for '" + clNameDGV.SelectedRows.Item(0).Cells(0).Value + "'." + vbNewLine + "Do you want to enter new user details ?", "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
            Dim nf As New CreateUser
            nf.TopMost = True
            nf.ShowDialog(Me)
        End If

    End If

    Dim nf1 As New LoginForm
    nf1.TopMost = True
    nf1.ShowDialog(Me)
    conn.Close()
End Sub

我的datagridview中只有一列有多行。我在datagridview的doubleclick事件上运行上面的函数。

1 个答案:

答案 0 :(得分:1)

由于你有一个单列DGV,你只需要使用.SelectedCells属性,你应该检查只选择了一个单元格,如下所示:

Private Sub ChUser()

    If clNameDGV.SelectedCells.Count <> 1 Then
        ' not exactly one row was selected
        Exit Sub
    End If

    Dim clinicName As String = CStr(clNameDGV.SelectedCells.Item(0).Value)
    Dim nFoundRecords As Integer
    Dim conn As SqlConnection = Nothing

    Try
        conn = New SqlConnection(conStr)
        conn.Open()
        myConn.clName = clinicName

        Dim sql As String = "SELECT COUNT(*) FROM Login_Detail WHERE Clinic_Name = @ClinicName"

        Using cmd As New SqlCommand(sql, conn)
            'TODO: Set the .SqlDbType parameter correctly.
            'TODO: Add the .Size parameter to match the setting in the database.
            cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@ClinicName", .SqlDbType = SqlDbType.NVarChar, .Value = clinicName})
            nFoundRecords = CInt(cmd.ExecuteScalar())
        End Using

        conn.Close()

    Finally
        If conn IsNot Nothing Then
            conn.Dispose()
        End If

    End Try

    If nFoundRecords = 0 Then
        Dim message As String = "No User Information found for '" & clinicName & "'." & vbNewLine & "Do you want to enter new user details?"
        Dim userChoice As DialogResult = MessageBox.Show(message, "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question)

        If userChoice = DialogResult.OK Then
            Dim nf As New CreateUser
            nf.TopMost = True
            nf.ShowDialog(Me)
        End If

    End If

    Dim nf1 As New LoginForm
    nf1.TopMost = True
    nf1.ShowDialog(Me)

End Sub

请注意我在适当的地方使用CStrCInt的方法。如果您使用Option Strict On,那么它会指出您应该在哪里进行显式转换(以及其他内容)。此外,我将一些行分成几行,以便于阅读,因此更容易编辑。