2013-10-16 24 views
0

我想通过datagridview行的单元格值与用户按下相同的keychar开始。代码娄的作品,但它不会选择移到下一行开头相同的字母时,我按相同字母第二,第三次......移动通过按键上的datagridview行

 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 
+0

我已经更新了我的代码,但它仍然不会遍历所有以相同字母开头的行。 – Dave

回答

0

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

你可以用你写的代码从来没有得到任何东西比匹配键的第一行。之后,无论您按多少次都无所谓。

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