指数超出范围。我试图将选定的行放在frm_Guest
到frm_Main
:
Private Sub dgview_GPIGuest_CellContentClick_1(sender As Object, e As
DataGridViewCellEventArgs) Handles dgview_GPIGuest.CellContentClick
Dim ID As String = dgview_GPIGuest.SelectedRows(0).Cells(0).Value.ToString()
Dim FName As String = dgview_GPIGuest.SelectedRows(0).Cells(1).Value.ToString()
Dim LName As String = dgview_GPIGuest.SelectedRows(0).Cells(2).Value.ToString()
Dim Gender As String = dgview_GPIGuest.SelectedRows(0).Cells(3).Value.ToString()
Dim Address As String = dgview_GPIGuest.SelectedRows(0).Cells(4).Value.ToString()
Dim IDType As String = dgview_GPIGuest.SelectedRows(0).Cells(5).Value.ToString()
Dim IDNumber As String = dgview_GPIGuest.SelectedRows(0).Cells(6).Value.ToString()
frm_Main.txt_GPIId.Text = ID
frm_Main.txt_GPIFirstName.Text = FName
frm_Main.txt_GPILastName.Text = LName
frm_Main.txt_GPIAddress.Text = Address
frm_Main.txt_GPIIDNumber.Text = IDNumber
frm_Main.txt_GPIIdType.Text = IDType
If Gender = "Male" Then
frm_Main.rb_GPIMale.Checked = True
Else
frm_Main.rb_GPIFemale.Checked = True
End If
End Sub
答案 0 :(得分:0)
我认为选择行和单元格点击之间存在混淆。通过单击网格的最左侧列来选择行。整行将突出显示。单击单个单元格时,没有选定的行;因此索引0超出范围。如果您想使用此活动,请使用DataGridViewCellEventArgs
作为@jmcilhinney建议。
Debug.Print($"Row {e.RowIndex.ToString}, Column {e.ColumnIndex}")
答案 1 :(得分:0)
首先,不确定您是否已经这样做但是必须在设计时或后面的代码中将SelectionMode
属性设置为FullRowSelect
:
Dgvw1.SelectionMode = DataGridviewSelectionMode.FullRowSelect
原因是当您单击一个单元格时选择整行。
继续,这里使用SelectedRows
是非常必要的(假设未设置MultiSelect
)。到目前为止我所理解的是你想得到所选行的列值,对吧?这是一个快速代码:
Dim row = dataGridView1.CurrentCell.RowIndex; ''This gets the row index(or count) of the selected row
Dim col = dataGridView1.CurrentCell.ColumnIndex; ''This gets the column index(or count) of the selected row
Dim ID As String = dataGridView1.Rows(row).Cells(col).Value.ToString()) ''Now note that here i am getting the selected column/cell's value, you can change it with any required index :)
希望这有帮助。
您收到错误的原因
理解起来非常简单。这有点像你试图从0中减去1,这将导致-1但在编程中(在集合的情况下),它是一个无效的值。我假设当你选择一个单元格时,你的整行没有被选中(默认行为)(阅读修复答案的开头)。这就是为什么SelectedRows()
,它应该返回所有选定的行,返回null。最后你得到了错误