Search datagridview on user keypress

前端 未结 5 1283
别跟我提以往
别跟我提以往 2021-02-09 05:09

I\'m trying to select the first row where the cell value starts with the same keychar the user pressed. That\'s the part that is giving me trouble.

Here\'s how I\'m hand

5条回答
  •  自闭症患者
    2021-02-09 05:21

    I use this in VB.NET. You can use http://www.developerfusion.com/tools/ to convert to C Sharp.

    I wrote a method that will select row letter typed. The function is called in the KeysPress event handler of the DataGridView.

    Method:

    'user types letter in dgv, method will select the column starting with that letter if it exists or else next letter existing in dgv
    Public Shared Sub GoToLetterTypedInDataGridView(ByVal dgv As DataGridView, ByVal columnName As String, ByVal columnPosition As Integer, ByVal letterTyped As Char)
        Try
            Dim dt As DataTable = dgv.DataSource
            Dim letter As Char = letterTyped
            Dim dv As DataView = New DataView(dt)
            Dim hasCount As Boolean = False
    
            While (Not hasCount)
                dv.Sort = columnName
                dv.RowFilter = columnName & " like '" & letter & "%'"
                If dv.Count > 0 Then
                    hasCount = True
                    Dim x As String = dv(0)(columnPosition).ToString()
                    Dim bs As New BindingSource
                    bs.DataSource = dt
                    dgv.BindingContext(bs).Position = bs.Find(columnName, x)
                    dgv.CurrentCell = dgv(0, bs.Position)
                Else
                    If letter = "z" Then
                        letter = "a"
                    ElseIf letter = "Z" Then
                        letter = "A"
                    Else : letter = Chr(Asc(letter) + 1)
                    End If
                End If
            End While
        Catch ex As Exception
            Dim stackframe As New Diagnostics.StackFrame(1)
            Throw New Exception("An error occurred in routine, '" & stackframe.GetMethod.ReflectedType.Name & "." & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'." & Environment.NewLine & "  Message was: '" & ex.Message & "'")
        End Try
    End Sub
    

    Then to call:

    Private Sub dgvNew_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles dgvNew.KeyPress
    Try
        If dgvNew.RowCount > 0 Then
            GoToLetterTypedInDataGridView(dgvNew, "columnName", 0, e.KeyChar)
        End If
    Catch ex As Exception
        Dim stackframe As New Diagnostics.StackFrame(1)
        Throw New Exception("An error occurred in routine, '" & stackframe.GetMethod.ReflectedType.Name & "." & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'." & Environment.NewLine & "  Message was: '" & ex.Message & "'")
    End Try
    

    End Sub

    Hope this helps! Amber

提交回复
热议问题