在输入键事件的变量中获取vb.net中datagridview的所有列值

时间:2013-10-29 13:50:34

标签: vb.net winforms datagridview

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

1 个答案:

答案 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