这似乎是一个重复的问题,但我正在寻找一个特定的功能。我查看了 StackOverflow 和 Google 上的类似问题,并尝试使用许多不同的代码示例,但到目前为止,还没有成功?
我在做什么:
- 在运行时,即
Form1_Load
,我调用一个函数在 DataGridView 中显示“MyFolder”中所有文件的文件信息。 - 我使用 Next/Previous 按钮循环浏览 DGV 行。
我的代码:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'Call Function To Display File Info From MyFolder:
DataGridView1.DataSource = Fileinfo_To_DataTable("C:\Users\" + username + "\Documents\MyApp\MyFolder")
End Sub
'Next Button:
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If DataGridView1.SelectedRows(0).Index < DataGridView1.RowCount - 1 Then
MyDesiredIndex = DataGridView1.SelectedRows(0).Index + 1
Else
MyDesiredIndex = 0
End If
DataGridView1.ClearSelection()
DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
DataGridView1.Rows(MyDesiredIndex).Selected = True
End Sub
'Previous Button:
Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
If DataGridView1.CurrentCell.RowIndex >= 0 And DataGridView1.CurrentCell.RowIndex <= DataGridView1.Rows.Count - 1 Then
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Or vbNull Then
MyDesiredIndex = DataGridView1.SelectedRows(0).Index - 1
End If
Next
End If
DataGridView1.ClearSelection()
DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
DataGridView1.Rows(MyDesiredIndex).Selected = True
End Sub
问题:
Next按钮以“连续循环”循环通过所有 DGV 行,无一例外。“连续循环”是指我的程序循环遍历所有行而不会停止,无论是在第一行 (0) 还是在最后一行(即,只要我继续按下 Next 按钮,就会发生循环)。
只有当我第一次使用 Next 按钮更改所选行(即 First > Last)时,Previous 按钮才有效。然后,点击Previous 按钮将所选行更改为返回到第一行(即Last > First)。但是,当程序到达第一行时,它会抛出如下异常:
“System.ArgumentOutOfRangeException:'索引超出范围。必须为非负数且小于集合的大小。参数名称:索引'”
- 解决超出范围异常。
- 解决所有行的循环/循环问题?
我尝试过的:
除了我上面的尝试(和许多其他尝试)之外,我在 StackOverflow 上找到了以下代码,它解决了同样的问题,但它也停在第一行而不循环遍历所有行:
移至 datagridview
中的上一行 移至 datagridview 中的上一行
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer = DataGridView1.CurrentRow.Index - 1
If i < 0 Then i = 0
DataGridView1.CurrentCell = Me.DataGridView1.Rows(i).Cells(0)
DataGridView1.Rows(i).Selected = True
End Sub
期望的行为:
我将不胜感激任何帮助,以使上一个按钮的行为方式与下一个按钮的行为方式相同,即连续循环遍历所有行而不会引发异常。
我做了很多尝试来寻找逻辑来“包含”该范围内先前行的选择,但没有成功。但是,我真的很喜欢 Next 按钮在行中连续循环而不停止的方式,并且希望将此行为复制到 Previous 按钮,以便能够在不停止的情况下连续循环两种方式(即 Next/Previous)?我也尝试了几个不同的For Each
循环,但无法让代码以所需的方式工作?
有谁知道我如何实现这一目标?