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中得到错误,因为它抛出索引超出范围。请告诉我,我是什么意思做错了。
答案 0 :(得分: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