how to put focus on TextBox when the form load?

前端 未结 16 1147
清歌不尽
清歌不尽 2020-12-04 14:59

I have in my C# program textBox

I need that when the program start, the focus will be on the textBox

I try this on Form_Load:

MyTextBox.Focus         


        
相关标签:
16条回答
  • 2020-12-04 15:25

    You could try:

    MyTextBox.Select();

    According to the documentation:

    The Select method activates the control if the control's Selectable style bit is set to true in ControlStyles, it is contained in another control, and all its parent controls are both visible and enabled.

    You can first check if the control can be selectable by inspecting the MyTextBox.CanSelect property.

    0 讨论(0)
  • 2020-12-04 15:27

    Finally i found the problem i was using metro framework and all your solutions will not work with metroTextBox, and all your solutions will work with normal textBox in load , show , visibility_change ,events, even the tab index = 0 is valid.

       // private void Form1_VisibleChanged(object sender, EventArgs e)
       // private void Form1__Shown(object sender, EventArgs e)
        private void Form1_Load(object sender, EventArgs e)
        {
    
            textBox1.Select();
            this.ActiveControl=textBox1;
            textBox1.Focus();
        }
    
    0 讨论(0)
  • 2020-12-04 15:28

    Set theActiveControl property of the form and you should be fine.

    this.ActiveControl = yourtextboxname;
    
    0 讨论(0)
  • 2020-12-04 15:29

    You cannot set focus to a control if it has not been rendered. Form.Load() occurs before the controls are rendered.

    Go to the form's events and double click the "Shown" event. In the form's shown event handler call the control.Focus() method.

        private void myForm_Shown(object sender, EventArgs e)
        {
            // Call textbox's focus method
            txtMyTextbox.Focus();
        }
    
    0 讨论(0)
  • 2020-12-04 15:30

    on your form, go to properties and make sure that "TopMost" property is set to true, that will solve your problem.

    0 讨论(0)
  • 2020-12-04 15:35

    I solved my problem with changing "TabIndex" property of TextBox. I set 0 for TextBox that I want to focus it on Form when the program start.

    0 讨论(0)
提交回复
热议问题