2016-02-12 139 views
2

我有了一個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它將提供所需的輸出 –

回答

1

清除按鈕點擊後,您已經擁有了您的txtMiles。至於啓動,請在您的加載方法中設置txtMiles.Focus()。

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

你應該確保你的TabIndex作爲集,然後代替Focus(),嘗試使用Select()。看到這個MSDN link

txtMiles.Select(); 

還要確保在視圖文件中沒有設置TabStop = true屬性。

1

這是舊的,但有人可能需要這個。

Control.Focus()被竊聽。如果它不工作,嘗試解決方法:

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

更改功能參數,以便他們將與你的控制工作,並記住你的控制的接受tab = true屬性。