0
Private Sub dgcustomerlist_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgcustomerlist.KeyPress
    Dim custcode As String
    Dim custname As String
    Dim custmobile As String
    'Dim rows As DataGridViewRow = dgcustomerlist.SelectedRows(0)


    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
        custcode = dgcustomerlist.SelectedCells(0).Value
        custname = dgcustomerlist.SelectedCells(1).Value
        custmobile = dgcustomerlist.SelectedCells(2).Value
        MsgBox("the selected value is", custcode)
    End If

继承人上面的代码,情况是我想要特定变量中gridview中所选行的列值。但是我在custname中遇到错误,因为它抛出了超出范围的索引。请告诉我我做错了什么。

4

1 回答 1

0

出现此错误是因为代码运行时未选择 CustName 单元格(可能是因为按 ENTER 取消选择它)。

您可以设置DataGridView.SelectionMode = DataGridViewSelectionMode.FullColumnSelect,也可以使用.CurrentRow.Cells代替.SelectedCells; 例如:

custcode = dgcustomerlist.CurrentRow.Cells(0).Value
custname = dgcustomerlist.CurrentRow.Cells(1).Value
custmobile = dgcustomerlist.CurrentRow.Cells(2).Value
于 2013-10-29T14:24:31.523 回答