views:

11876

answers:

5

Say I have a Textbox nested within a TabControl.

When the form loads I would like to focus on that textbox (by default the focus is set to the tabControl).

Simply calling textbox1.focus() in the Load event of the form does not appear to work.

I have been able to focus it by doing the following:

 private void frmMainLoad(object sender, EventArgs e)
 {
     foreach (TabPage tab in this.tabControl1.TabPages) 
     {
         this.tabControl1.SelectedTab = tab;
     }
 }

My question is:

Is there a more elegant way to do this?

+1  A: 

Haven't tested, haven't checked, but my instinct tells me it might be a good idea to attach to an event coming from the tab page's initialization event itself, as it is the container that's showing and the form's load event might be too early.

Also, I can't seem to understand what your code does and how it helps you do what you want done. Could you please elaborate?

Omer van Kloeten
+13  A: 

The following is the solution:

private void frmMainLoad(object sender, EventArgs e)
{
    ActiveControl = textBox1;
}

The better question would however be why... I'm not entirely sure what the answer to that one is.

Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.

samjudson
+5  A: 

Try putting it in the Form_Shown() event. Because it's in a container, putting in the Form_Load or even the Form() constructor won't work.

Korby
+1 Its works, but I'm interested to know why?
Jon Mitchell
It does not work in Load because after load, the controls are re-focused according to tab order and the focused control is "overwritten". When you focus the control in Shown, there is nothing that would "overwrite" your call by focusing another control.
Marek
A: 

You just need to add the Control.Select() for your control to this code. I have used this to set focus on controls during validation when there are errors.

private void ShowControlTab(Control ControlToShow)
    {
        if (!TabSelected)
        {
            if (ControlToShow.Parent != null)
            {
                if (ControlToShow.Parent.GetType() == typeof(TabPage))
                {
                    TabPage Tab = (TabPage)ControlToShow.Parent;
                    if (WOTabs.TabPages.Contains(Tab))
                    {
                        WOTabs.SelectedTab = Tab;
                        TabSelected = true;
                        return;
                    }
                }

                ShowControlTab(ControlToShow.Parent);
            }
        }
    }
bdwakefield
A: 

Try to use textbox1.Select() instead of textbox1.Focus(). This helped me few times.

Mikhail G