2
votes

I have a form just with a textbox and a datagridview. I would like when user pressed an arrow (up/down) it browses through datagridview and when user pressed any other key it sends to textbox.

It's not working, when datagridview has focus and user press a letter key, it changes focus to textbox, but no text is sent.

My code:

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
If keyData = Keys.Down Or keyData = Keys.Up Then
  grid.Focus()
  Return MyBase.ProcessCmdKey(msg, keyData)
ElseIf Not Me.ActiveControl.Equals(txtFiltro) Then
  Me.ActiveControl = txtFiltro
  txtFiltro.Focus()
  txtFiltro.Select()
  Return MyBase.ProcessCmdKey(msg, keyData)
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function

The key is sent before change focus... :(

1

1 Answers

0
votes

You'll want to make sure you have the property "KeyPreview" set to true on the form that has your DataGridView and TextBox.

Then on your KeyDown event for your form try something like this:

    Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then

        DataGridView1.Focus()
    Else
        e.Handled = True

        TextBox1.Focus()

        If TextBox1.TextLength = 0 Then
            TextBox1.Text += ChrW(e.KeyValue)
            TextBox1.SelectionStart = 1
        End If
    End If
End Sub

The last part will trap to see if you want whatever key was pressed to be passed to the text box. It could be ignored if you don't need that. Then if you go back to using the arrow keys it should refocus to the DataGridView.

Probably not exactly what you're looking for. But I think it can get you on the right track.