C # Make Enter key jump to either textBox or comboBox field

0

How can I do in a function, that when the person gives enter, it jumps to the field below, which can be both a combobox and a textbox?

I currently have this function, but it jumps to the last textbox, thus logging in, without going through the combobox first

public void pulaProxCampo(object sender, KeyEventArgs e) 
{
    if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) 
    {
       this.SelectNextControl((Control)sender, true, true, true, true);
    }
}

Do you need to do a field validation to see if they are empty?

    
asked by anonymous 23.02.2017 / 14:06

3 answers

2

A very common solution is to make the Enter act as Tab. To work correctly will depend on the tab order of the controls. And put TabStop to false in those that should not receive focus.

public void pulaProxCampo(object sender, KeyEventArgs e) 
{
    if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) 
    {
       SendKeys.Send("{TAB}");
    }
}

link link

    
23.02.2017 / 15:08
1

Your code is correct and functional. The problem here is that your container controls do not have the TabOrder correct.

Then, change the TabOrder property of your controls to follow the order you want.

Another important point is that the code above goes through all elements, even those with TabStop set to false . This will cause Tab and Enter to have different behaviors.

The method SelectNextControl receives 5 parameters, which are

  • Control ctrl : The control by which the search will start.

  • If this property is bool forward , the controls with true will be ignored, false pro otherwise.
  • bool tabStopOnly : Defines whether child controls should be selected. Example: There is true and TabStop = false ; if this property is set to false the cells of nested will also be selected.

  • 23.02.2017 / 17:15
    1

    You can explicitly jump to a particular control using the Focus () of that control .

    public void pulaProxCampo(object sender, KeyEventArgs e) 
    {
        if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return)) 
        {
            if(deveSaltarParaTextBox)
            {
                textBox.Focus();
            }
            else
            {
                combobox.Focus();
            }
        }
    }
    

    Note: Use this approach only if the jump does not follow the path defined by TabOrder.

        
    23.02.2017 / 17:53