【问题标题】:VB.Net Must be non-negative and less than the size of the collectionVB.Net 必须是非负数且小于集合的大小
【发布时间】:2018-05-05 10:18:48
【问题描述】:

索引超出范围。我试图将选定的行放在frm_Guestfrm_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

【问题讨论】:

  • 请格式化您的问题
  • 那么抛出​​异常时的索引是多少,集合的大小是多少?最有可能的问题是您不了解DataGridView 中选定的行是什么。在这种情况下,您不应该使用 SelectedRowse 参数为您提供单击其内容的单元格的列和行的索引。这就是你应该使用的。

标签: vb.net


【解决方案1】:

我认为混淆是在选定的行和单元格单击之间。通过单击网格的最左列选择一行。整行将突出显示。单击单个单元格时,没有选定的行;因此索引 0 超出范围。如果您想使用此事件,请按照@jmcilhinney 的建议使用DataGridViewCellEventArgs

Debug.Print($"Row {e.RowIndex.ToString}, Column {e.ColumnIndex}")

【讨论】:

  • When a single cell is clicked there are no selected rows - 如果SelectionMode 设置为FullRowMode 或启用FullRowSelect 会怎样?
  • 好吧,我想这不是因为 OP 使索引超出范围。
  • 可能是......或者不可能...... OP甚至没有提到他在哪里得到错误
【解决方案2】:

首先,不确定您是否已经这样做了,但您必须在设计时或从后面的代码中将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。最后你得到错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多