views:

172

answers:

1

I'd like give focus to a textBox after a Tab has been selected but no matter what I try it doesn't work. I've looked at similar questions here but they don't get me the results I need. Here is what Ive tried.

    private void tabBDERip_Click(object sender, EventArgs e)
    {
        textBoxPassword.Focus();
    }

and

    private void tabAll_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (tabAll.SelectedTab == tabBDERip)
        {
            textBoxPassword.Focus();
        }
    }

Can someone please tell me what I'm doing wrong?

Thanks

+1  A: 

First thing the Click event of the TabPage control fires when the user clicks inside the TabPage not on the header so your SelectedIndexChanged event is the one you want to use.

I just tested code very similiar to yours:

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (tabControl1.SelectedTab == tabPage2)
    {
        textBox4.Focus();
    }
}

And it worked fine.

Is the password textbox not enabled or something like that?

If you try to call Focus() on a different control does that also not work?

If you set a breakpoint inside the SelectedIndexChanged code does it get hit?

Update: Interesting. If the breakpoint isn't getting hit (before the if) I would double check that your eventhandler is properly attached. Look in your designer.cs for something like:

this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);

Update: I put my working example at http://www.ccswe.com/temp/SO_TextBoxFocus.zip maybe looking at it will help you figure out where the issue is.

Update: The easier way to attach an event handler to a control on your form:

1: Select the Control to want to attach an event handler to and then click the Events icon (lightning bolt) in the Properties window.

alt text

2: Find the event you want to attach to and double click to the right.

alt text

3: A code stub will be automatically generated for you and the event will be attached in the designer.

alt text

If you look at the properties window again you'll now see the name of the method that was generated.

Cory Charlton
Thanks for the reply Cory. No it doesn't get hit after all. I even created an app with just one textBox, and a tabControl with only 2 tabs. Still doesn't get hit.
JimDel
Ahh! That was it Cory. Added your update and it works great. I'm still new at this and didn't know that needed to be there. But now that I look at it it makes sense. Thanks again.
JimDel
Glad I could help. Editing the designer isn't the easiest way of attaching an event handler. You can do it through the properties window. I'll update my answer with more info on that.
Cory Charlton
Thanks for the additional info Cory!
JimDel