DataGridView从下向上循环

时间:2018-06-25 13:05:45

标签: vb.net datagridview

当我在下面运行代码时,返回的所选行始终是自下而上的。如何使它每次都从Data Grid表的顶部循环?

'Find the selected customer by code. Display closest match in grid.
       Dim targetString As String = txtAccountCode.Text

       For Each row As DataGridViewRow In frmCustomerLookUp.GSCUSTDataGridView.Rows

            If row.Cells(0).Value.ToString().StartsWith(targetString) Then

                frmCustomerLookUp.GSCUSTDataGridView.ClearSelection()
                frmCustomerLookUp.GSCUSTDataGridView.Rows(row.Index).Selected = True
                frmCustomerLookUp.GSCUSTDataGridView.FirstDisplayedScrollingRowIndex = frmCustomerLookUp.GSCUSTDataGridView.SelectedRows(0).Index

                Dim selectedIndex = frmCustomerLookUp.GSCUSTDataGridView.SelectedRows(0).Index
                frmCustomerLookUp.GSCUSTDataGridView.Rows(selectedIndex).Selected = True
                frmCustomerLookUp.GSCUSTDataGridView.Rows(selectedIndex).Cells(0).Selected = True

                Exit Sub

            End If

        Next

2 个答案:

答案 0 :(得分:0)

使用For ... Next循环,从最后一行开始,步进-1

For index As Integer = frmCustomerLookUp.GSCUSTDataGridView.Rows.Count - 1 To 0 Step -1 ' Or Count -2
    If frmCustomerLookUp.GSCUSTDataGridView.Rows(index).Cells(0).Value.ToString().StartsWith(targetString) Then

答案 1 :(得分:0)

正如另一个人所说。 (只是短一点)

For x=frmCustomerLookUp.GSCUSTDataGridView.Rows.Count - 1 To 0 Step -1
    if frmCustomerLookUp.GSCUSTDataGridView(0,x).ToString().StartsWith(targetString) then
        'something
    end if
next