Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on a Control When Switching Tabs

Tags:

c#

.net

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.

like image 473
Benjamin Autin Avatar asked Dec 31 '22 09:12

Benjamin Autin


2 Answers

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();
   }
}
like image 186
itsmatt Avatar answered Jan 10 '23 17:01

itsmatt


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();
            }
        }
like image 43
CheGueVerra Avatar answered Jan 10 '23 15:01

CheGueVerra