0

In a standard WinForms application, is it possible to have a scenario like the following and how would I do it:

A form with four textbox controls, arranged on the form from top to bottom:

  • TextBox1
  • TextBox2
  • TextBox3
  • TextBox4

The desired behavior is that when the form loads, the focus is on TextBox3, but when tabbing out, the focus goes to the top and goes through all controls as normal, in the following way:

  1. TextBox3
  2. TextBox1
  3. TextBox2
  4. TextBox3
  5. TextBox4

5 Answers 5

1

This would be something that you'll need to code up and it will require proper usage of events. Set your tab order as you would want it and then code up the following:

private bool OnLoad = True;

Form_OnLoad(...) {
    TextBox3.SetFocus();
}

TextBox3_LostFocus(...) {
    if (OnLoad) {
        TextBox1.SetFocus();
        OnLoad = false;
    } // The else falls through to the default tab order
 }
2
  • I was thinking this is the way to go, to have a "is this the first time?" flag but I wanted to avoid it if possible. Jun 3, 2009 at 14:42
  • @krolley - I doubt there is a way to avoid the "first time" flag and it is likely going to be cleaner and easier to understand than the manipulation of TabIndexes Jun 3, 2009 at 14:45
1

LFSR is right:

You must code on textBox3 LostFocus event, this is a VB example

static notFirstTime as boolean
if notFirstTime then exit sub
textbox1.setFocus
notfirstTime=true
0

Short answer: absolutely!

The layout on the form has nothing to do with the tab order. You specify the tab traversal--and the starting point--just by setting the TabIndex property. The starting control should get a 0, the next a 1, and so forth. Also the TabStop property is handy for specifying which controls should be reachable by the Tab key.

0

You might be able to trick this into working buy using the following configuration of TabIndex properties.

  • Label for Textbox 3 = 1
  • TextBox1 = 2
  • TextBox2 = 3
  • TextBox3 = 4
  • TextBox4 = 5

You will have to set the label to have TabStop="True". But I think this MIGHT work. Please keep in mind that I am not 100% sure on this...

1
  • It is a contrived example, but unfortunately the textboxes do not have labels. Jun 3, 2009 at 14:44
0

In your constructor (or designer) Set the tabl indexes like this (or something like this).

this.textBox1.TabIndex = 1;
this.textBox2.TabIndex = 2;
this.textBox3.TabIndex = 0;
this.textBox4.TabIndex = 4;

Then setup an event to set the tabIndex of textbox 3 to the new value:

private void textBox3_Leave(object sender, EventArgs e)
{
    textBox3.TabIndex = 3;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.