TransWikia.com

Set focus to another Control

Stack Overflow Asked by Binu on August 4, 2020

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)

3 Answers

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

Answered by paywand dlshad on August 4, 2020

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)
{
...
}

Answered by Nikos Steiakakis on August 4, 2020

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

Answered by Taylor Leese on August 4, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP