Binu
Binu

Reputation: 1403

Set focus to another Control

i want to set focus from one textbox1 to another textbox2 while i am pressing ENTER key in textbox1 in C# windows application(c# 2005)

Upvotes: 1

Views: 3184

Answers (3)

paywand dlshad
paywand dlshad

Reputation: 11

add this to your form

protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            Control NextControl = this.GetNextControl(this.ActiveControl, true);
                while (!NextControl.TabStop || !NextControl.Enabled || !NextControl.Visible)
                {
                    NextControl=this.GetNextControl(NextControl, true);
                }
                NextControl.Focus();
        }
        else
        {
            base.OnKeyDown(e);
        }
    }

Upvotes: 1

Taylor Leese
Taylor Leese

Reputation: 52310

Handle the KeyPress or KeyDown event of textbox1 and then call textbox2.Focus().

Upvotes: 0

Nikos Steiakakis
Nikos Steiakakis

Reputation: 5745

First, you will have to set the KeyPreview property of the Form set to true. Then you will have to override the form's OnKeyDown method and make a case like:

if(e.KeyCode == Keys.Enter)
{
      Control ctlNext = this.GetNextControl(this.ActiveControl, true);
      ctlNext.Focus();
}
else
{
      base.OnKeyDown(e);
}

Mind you that this code will work for every control on the form, and move the focus to the next one. If you just want this code to work for the textboxes you could add a check like:

if(this.ActiveControl is TextBox)
{
...
}

Upvotes: 1

Related Questions