【问题标题】:C# set focus on textboxC# 将焦点设置在文本框上
【发布时间】:2016-05-23 06:26:42
【问题描述】:

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

提前感谢您的帮助。

【问题讨论】:

  • 无需设置txtMiles.Focus();仅在属性集 Tabindex 1 中以编程方式提供所需的输出

标签: c# textbox focus controls


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您应该确保您的 TabIndex 已设置,然后尝试使用 Select() 而不是 Focus()。看到这个MSDN link。

    txtMiles.Select();
    

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

    【讨论】:

      【解决方案3】:

      它很旧,但有人可能需要它。

      Control.Focus() 被窃听。如果它不起作用,请尝试解决方法:

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

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

      【讨论】:

        【解决方案4】:

        使用这个解决方案效果很好......

        txtMiles.Select();

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-21
          • 2016-07-23
          相关资源
          最近更新 更多