how to put focus on TextBox when the form load?

前端 未结 16 1102
清歌不尽
清歌不尽 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:37

    The reason you can't get it to work is because the Load event is called before the form is drawn or rendered.

    It like telling a pizza place how to make your pizza, and then asking them to send you a picture of how much pepperoni is on your pizza before they made it.

    using System;
    using System.Windows.Forms;
    
    namespace Testing
    {
        public partial class TestForm : Form
        {
            public TestForm()
            {
                InitializeComponent();
    
                Load += TestForm_Load;
    
                VisibleChanged += TestForm_VisibleChanged;
    
                Shown += TestForm_Shown;
    
                Show();
    
            }
    
            private void TestForm_Load(object sender, EventArgs e)
            {
                MessageBox.Show("This event is called before the form is rendered.");
            }
    
            private void TestForm_VisibleChanged(object sender, EventArgs e)
            {
                MessageBox.Show("This event is called before the form is rendered.");
            }
    
            private void TestForm_Shown(object sender, EventArgs e)
            {
                MessageBox.Show("This event is called after the form is rendered.");
                txtFirstName.Focus();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 15:37

    it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;

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

    Textbox.Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus().

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

    If you only want to set the focus the first time the form is shown, try handling the Form.Shown event and doing it there. Otherwise use Control.VisibleChanged.

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