C#将焦点设置文本框

C#将焦点设置文本框

问题描述:

我有了一个lblMiles,lblKM,txtMiles,lblResults,btnConvert,btnClear形式,btnExitC#将焦点设置文本框

我试图设置 “txtMiles” 文本框焦点后: (1 )的形式打开 (2)清除按钮被点击

时,我有标签的订单设置教师要“0”“btnConvert”选项卡顺序设置,并且他的指示状态“记得焦点回到英里当用户清除表格后显示公里后的文本框“&”。

我试过使用txtMiles.Focus();但它似乎不适合我。

*************此表格使用了代码*************************** ******

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Assignment3 
{ 
    public partial class MilesToKilometers : Form 
    { 
     // This sets the conversion value 
     const double CONVERSION = 1.61; 

     public MilesToKilometers() 
     { 
      InitializeComponent(); 
     } 

     private void txtMiles_TextChanged(object sender, EventArgs e) 
     { 

     } 

     private void MilesToKilometers_Load(object sender, EventArgs e) 
     { 

     } 

     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(); 
     } 
    } 
} 

在此先感谢您的帮助。

+0

无需设置txtMiles.Focus();编程方式只是在属性设置Tabindex 1它将提供所需的输出 –

清除按钮点击后,您已经拥有了您的txtMiles。至于启动,请在您的加载方法中设置txtMiles.Focus()。

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

你应该确保你的TabIndex作为集,然后代替Focus(),尝试使用Select()。看到这个MSDN link

txtMiles.Select(); 

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

这是旧的,但有人可能需要这个。

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

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

更改功能参数,以便他们将与你的控制工作,并记住你的控制的接受tab = true属性。