C# Make Enter key jump to either textbox or combobox field

Asked

Viewed 2,316 times

0

How can I do in a function, that when the person der enter , he jumps to the bottom field , which can be both a combobox and a textbox?

I currently have this function , but it jumps to the last textbox , doing so log 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 or need to do a field validation to see if they are empty?

  • 1

    I always find it best to teach users to use the tab key

3 answers

2

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

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

https://msdn.microsoft.com/pt-br/library/system.windows.forms.sendkeys(v=vs.110). aspx https://msdn.microsoft.com/pt-br/library/system.windows.forms.control.tabstop(v=vs.110). aspx

1

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

So, change the property TabOrder of your controls to follow the desired order.

Another important point is that the above code goes through all elements, even those that have TabStop defined as false. This will make the Tab and the Enter have different behaviors.

The method SelectNextControl receives 5 parameters, being them

  1. Control ctrl: The control by which the search will begin.

  2. bool forward: Sets if the search goes next control (true) or to the previous (false)

  3. bool tabStopOnly: If that property is true the controls with TabStop = false will be ignored, false otherwise.

  4. nested: Sets if child controls should be selected. Example: There is a TextBox and DataGridView; if this property is defined as true the cells of DataGridView will also be selected.

  5. wrap: Sets if the search starts again when arriving at the last control of the container.

1

You can explicitly jump to a certain control using the method Focus() 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 course defined by Taborder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.