I created a form with a label, textbox and a button. In the form load event I called the focus() function for the textbox. But when I run my code the cursor is not coming to textbox. I need the cursor to go to text box as soon as the form is loaded. How to do it?
When showing a form that contains a TextBox, it's common courtesy to focus the TextBox so that the user can begin typing immediately. To focus a TextBox when a Windows Form first loads, simply set the TabIndex for the TextBox to zero (or the lowest TabIndex for any Control on the Form).
Setting the focus means making the field active so the cursor is blinking and ready to accept text input. This method can also be used to make a text field active when something else happens (see below).
If you simply need to make sure a certain control gets focus when you first load a form, then change the TabOrder
properties of all your controls (in the Designer) so that the control in question is '0', and the other elements are going up from there, '1', '2', etc.
If you need to dynamically select a different control when you show a form depending on some condition, then use the following code:
private void Form1_Load(object sender, EventArgs e) {
// You need to show the form otherwise setting focus does nothing
// (there are no controls to set focus to yet!)
this.Show()
if (someCondition == true)
control.Focus();
else
control2.Focus();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With