tags:

views:

349

answers:

6

I want to detect when tab key is pressed in a textBox and focus the next textbox in the panel.

I have tried out keyPressed method and keyDown method. But when I run the program and debug those methods are not calling when the tab key is pressed. Here is my code.

private void textBoxName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        textBoxUsername.Focus();
    }
}

private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar==(char)Keys.Tab)
    {
        textBoxUsername.Focus();
    }
}

Please correct me.Thank you.

+7  A: 

Why do you need that complication at all? WinForms does it for you automatically. You just need to set the correct tab order.

Fyodor Soikin
how do I put the correct tab order?It's automatically placing in the wrong order that's why I wanted to do it manually.
Use the TabIndex property on the control. You can set this programmatically or you can use View -> Tab Order in the designer.
Nathan Tomkins
+1  A: 

You should use tabOrder instead.

VoodooChild
A: 

You want the "leave" event. I just threw this into the default C# WinForms application:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        /* 
              ... misc housekeeping ... 
        */

        private void OnLeave(object sender, EventArgs e)
        {
            lblMsg.Text = "left field 1";
        }

        private void OnLeave2(object sender, EventArgs e)
        {
            lblMsg.Text = "left field 2";
        }
    }
}

It works as you would expect. Obviously you can do anything you want in the Leave() handler, including forcing the focus elsewhere, but be careful not to confuse the user...

egrunin
A: 

If textBoxName has a focus while pressing the TAB Key , then only the "KeyDown" event triggers. You just need to set the correct tab order.

A: 

You can try overriding the ProcessCmdKey method like this

Veer
A: 

go to the properties of text box and assign correct order of tabindex

sravan