0

我正在尝试遍历 datagridview 行,其中单元格值以用户按下的相同 keychar 开头。下面的代码有效,但是当我第二次、第三次按下相同的字母时,它不会将选择移动到以相同字母开头的下一行...

     Private Sub dataGridView1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles dgw.KeyPress
    If [Char].IsLetter(e.KeyChar) Then
        For i As Integer = 0 To (dgw.Rows.Count) - 1
            If dgw.Rows(i).Cells(1).Value.ToString().StartsWith(e.KeyChar.ToString(), True, CultureInfo.InvariantCulture) Then
                If lastKey = e.KeyChar And lastIndex < i Then
                    Continue For
                End If

                lastKey = e.KeyChar
                lastIndex = i
                dgw.Rows(i).Cells(1).Selected = True
                Return

            End If

        Next
    End If
End Sub
4

2 回答 2

0

似乎是逻辑上的缺陷。您按下键,保存索引并中断。然后你按同一个键。如果 lastIndex 小于 i 你继续。这意味着它只会选择它找到的第一行,其值小于最后一行。更改为 lastindex > i 你应该没问题。

您可以使用您编写的代码,除了与键匹配的第一行之外,永远不会得到任何其他内容。之后,按多少次都没关系。

于 2013-10-21T07:59:23.373 回答
0

我知道这篇文章太旧了……无论如何,我已经找到了解决方法,也许它对某人有用。

public lastkey as string


    Private Sub dataGridView1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles dgw.KeyPress

                            Dim input = StrConv(e.keychar.toString()
                            lastkey += input
                            Dim found as Boolean    


                      if StrConv(dgw.currentCell.Value.toString.Substring(0,1), VbStrConv.UpperCase) = input then
                            dim curIndex = dgw.currentRow.Index
                            if curIndex < dgw.rows.count - 1 then
                                dgw.ClearSelection()
                                curIndex += 1
                                dgw.currentCell = dgw.rows(curIndex).Cells(0)
                                dgw.rows(curIndex).selected = true
                            end if
                     else
                            dgv_jumpRecord(lastkey,found)

                            if not found then
                               lastkey = input
                               dgv_jumpRecord(lastkey,found)
                            end if   
                     End if         

   End Sub

    Public Sub dgv_jumpRecord(byVal lastkey as String, ByRef found as boolean)

                            For i As Integer = 0 To (dgw.Rows.Count) - 1

                            dim rowText = dgw.Rows(i).Cells(1).Value.ToString

                            If StrConv(rowText.ToString(),VbStrConv.UpperCase).StartsWith(lastkey) Then
                               dgw.ClearSelection()
                               dgw.CurrentCell = dgw.rows(i).Cells(0)
                               dgw.rows(i).selected = true
                               found = true
                               Exit Sub
                            End If

                            Next
                   found = false

 End Sub
于 2015-02-20T12:53:47.150 回答