How to shift the focus from one Textbox to the next?

Asked

Viewed 2,151 times

4

I’m trying to shift the focus of the field after the user writes 2 digits. Validation is ok, but I haven’t found a method to change focus.

NOTE: It is a dynamic method used for various fields, so I can’t specify in hand which control I want the focus.

Follow 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);
    }
}

2 answers

6


Use the method SelectNextControl() 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

  • Is that (Button) Sender correct? I don’t understand the use of it!

  • 1

    I switched to (Textbox) and it worked. Thank you very much!!!!

  • 1

    @Joaopaulo this example was taken from the article in MSDN. The standard signature of the method _Click() automatically implements the object sender - you can then switch to the value you need.

  • 1

    @Joaopaulo I’m happy to read this, it’s a pleasure to help. =)

0

Code:

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

Reference: Control.Keyup Event

Browser other questions tagged

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