tags:

views:

287

answers:

2

What I want to do is set the focus to a specific control (specifically a TextBox) on a tab page when that tab page is selected.

I've tried to call Focus during the Selected event of the containing tab control, but that isn't working. After that I tried to call focus during the VisibleChanged event of the control itself (with a check so that I'm not focusing on an invisible control), but that isn't working either.

Searching this site, I've come across this question but that isn't working either. Although after that, I did notice that calling the Focus of the control does make it the ActiveControl.

+3  A: 

I did this and it seems to work:

Handle the SelectedIndexChanged for the tabControl. Check if tabControl1.SelectedIndex == the one I want and call textBox.Focus();

I'm using VS 2008, BTW.


Something like this worked:

private void tabControl1_selectedIndexChanged(object sender, EventArgs e)
{
   if (tabControl1.SelectedIndex == 1)
   {
      textBox1.Focus();
   }
}
itsmatt
Thanks, this worked. Do you know why it doesn't work in the Selected event, but does in the SelectedIndex event?
toast
A tabcontrol steals focus on SelectedIndexChanged.
Barfieldmv
+1  A: 

Try the TabPage.Enter something like

        private void tabPage1_Enter(object sender, EventArgs e)
        {
            TabPage page = (TabPage)sender;
            switch (page.TabIndex)
            {
                case 0:
                    textBox1.Text = "Page 1";
                    if (!textBox1.Focus())
                        textBox1.Focus();

                    break;
                case 1:
                    textBox2.Text = "Page 2";

                    if (!textBox2.Focus())
                        textBox2.Focus();

                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
CheGueVerra