Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want when my windows form load cursor by default fpcus on a textbox named "ItemCodetextBox".
I have used tab Control and the textbox is on the tab control.
I have witten the following code on the form load event. But it does not work.
ItemCodetextBox.Focus();
Please help me.
Posted
Updated 7-Feb-14 18:51pm
v2

You cannot directly focus a control on form load (by the way, this is a fake event, you don't have to use it; it is added only to provide the same mechanism of adding handlers as for "real" events", using it is equivalent to adding code at the end of a form constructor). This is because only a visible control can be focused.

You can focus it when a form is shown for the first time. If written in the load event handler or a constructor, it would look like
C#
this.FormShown += (sender, eventArgs) => { myControl.Focus(); }


Alternatively, you can set "logical focus", which can be done in advance, in contrast to "real" focus:
C#
this.ActiveControl = myControl;


—SA
 
Share this answer
 
v3
Comments
BillWoodruff 8-Feb-14 1:49am    
+5 Excellent. It's a shame that the most popular books on WinForms (I was a technical editor for one published by Addison-Wesley) don't explain this as clearly, and succinctly, as you do here !
Sergey Alexandrovich Kryukov 8-Feb-14 1:52am    
Thank you very much, Bill.
—SA
 
Share this answer
 
v2
Try this

C#
private void Form1_Load(object sender, EventArgs e)
      {
          ItemCodetextBox.TabIndex = 0;
          ItemCodetextBox.Focus();
      }
 
Share this answer
 
v2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900