在keypress上移动datagridview行

时间:2013-10-16 11:21:48

标签: vb.net datagridview

我正在尝试浏览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

2 个答案:

答案 0 :(得分:0)

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

您可以使用您编写的代码,除了匹配密钥的第一行之外,不会得到任何其他内容。之后,按下多少次并不重要。

答案 1 :(得分: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