C#设置焦点在文本框上

Nat*_* E. 2 c# controls textbox focus

我试图设置"txtMiles"文本框以便在以下情况下聚焦:(1)单击清除按钮时窗体打开(2)

我试过使用txtMiles.Focus(); 但它似乎对我不起作用.

*************在本表格上使用的代码*****************************

        private void btnConvert_Click(object sender, EventArgs e)
        {
            //assigns variable in memory.
            double txtMile = 0;
            double Results;

            try
            {
                // here is where the math happens.
                txtMile = double.Parse(txtMiles.Text);
                Results = txtMile * CONVERSION;
                lblResults.Text = Results.ToString("n2");
                txtMiles.Focus();
            }
                // if the user enters an incorrect value this test will alert them of such.
            catch
            {
                //MessageBox.Show (ex.ToString());
                MessageBox.Show("You entered an incorrect value");
                txtMiles.Focus();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //This empties all the fields on the form.
            txtMiles.Text = "";
            txtMiles.Focus();
            lblResults.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
           // closes program
            this.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

Fan*_*oit 6

你应该确保你设置TabIndex,然后Focus()尝试使用Select().请参阅此MSDN链接.

txtMiles.Select();
Run Code Online (Sandbox Code Playgroud)

还要确保TabStop = true视图文件中没有设置属性.