C# 如何将焦点设置到文本框上

4

我正在尝试在以下情况下将“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();
        }
    }
}

Thanks in advance for the help.


1
只需在属性中设置 Tabindex 1,而不是在程序中设置 txtMiles.Focus();,即可获得所需的输出。 - Kutty Rajesh Valangai
4个回答

10

您应该确保设置了TabIndex,然后不要使用Focus(),而是尝试使用Select()。请参阅此MSDN链接

txtMiles.Select();

同时确保视图文件中没有设置TabStop = true属性。


4

虽然这已经是老内容了,但仍有人可能需要。

Control.Focus() 存在缺陷。如果不起作用,请尝试以下解决方法:

this.SelectNextControl(_controlname, true, true, true, true);

更改函数参数,使其与您的控件兼容,并记住您的控件的TabStop = true属性。


2

在单击清除按钮后,您已经将txtMiles聚焦。至于启动项,在load方法中设置txtMiles.Focus()。

private void MilesToKilometers_Load(object sender, EventArgs e)
{
    txtMiles.Focus();
}

0

使用这个解决方案完美地解决了问题...

txtMiles.Select();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接