在 Enter 键事件 vb.net 变量中获取数据网格视图的所有列值


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 中出现错误,因为它将索引抛出范围。请告诉我我做错了什么。

出现

此错误是因为代码运行时未选择 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

最新更新