Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms c# - Set focus to first child control of TabPage

Tags:

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?

like image 226
Corin Blaikie Avatar asked Sep 07 '08 18:09

Corin Blaikie


People also ask

Is Windows Form C#?

A Windows form in C# application is one that runs on the desktop of a computer. Visual Studio Form along with C# can be used to create a Windows Forms application. Controls can be added to the Windows forms C# via the Toolbox in Visual Studio. Controls such as labels, checkboxes, radio buttons, etc.

Will WinForms be deprecated?

WinForms won't be deprecated until Win32 is ... which could be quite sometime! WPF on the other hand has few direct dependencies on Win32 so could potentially form the basis of a "fresh start" UI layer on a future version of windows.


2 Answers

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.

like image 127
samjudson Avatar answered Sep 16 '22 11:09

samjudson


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.

like image 20
Korby Avatar answered Sep 16 '22 11:09

Korby