How to change focus from one TextBox to the next?

4

I'm trying to change the focus of the field after the user types 2 digits. Validation is ok, but I have not yet found a method to get focus shifted.

NOTE: This is a dynamic method used for multiple fields, so I can not specify on the hand which control I want to focus on.

Here's my attempt:

private void txt_TextChanged(object sender, EventArgs e)
{
    try
    {
        var campo = (TextBox) sender;

        if(campo.Text.Length == 2)
        {
            var campoSeguinte = Controls.Find("txtP1N19", true); 
            // Não achei um "seletor" para encontrar o proximo item pelo TabIndex ai 
            // busquei pelo nome para testar.

            Controls[0].Text = "11"; // Com o campo encontrado tentei interagir
            Controls[0].Focus();
            Controls[0].Select();               
            Controls[0].Update();

            // Mas dessa forma o campo encontrado não ficou com o valor 11 e nem com foco. 
            // Não aconteceu nada apesar de debugando eu vir que passou por todo o trecho

        }               
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
    
asked by anonymous 09.10.2015 / 14:44

2 answers

5

Use the SelectNextControl() method of the container containing the set of controls in question.

private void button1_Click(object sender, EventArgs e)
{
    Control p;
    p = ((Button) sender).Parent;
    p.SelectNextControl(ActiveControl, true, true, true, true);
}

Source: MSDN

link

    
09.10.2015 / 14:58
0

Code:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (textBox1.Text.Length == 2)
    {
        SendKeys.Send("{Tab}");
    }
}

Reference: Control.KeyUp Event

    
09.10.2015 / 14:58