Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I give focus to a textBox after a Tab has been selected?

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

like image 365
JimDel Avatar asked Dec 11 '25 00:12

JimDel


1 Answers

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 http://www.ccswe.com/temp/Attach_EventHandler_1.png

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

alt text http://www.ccswe.com/temp/Attach_EventHandler_2.png

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

alt text http://www.ccswe.com/temp/Attach_EventHandler_3.png

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

like image 162
Cory Charlton Avatar answered Dec 13 '25 13:12

Cory Charlton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!