2016-03-04 194 views
0

所以我還是很新的編程,我試圖創建一個程序,在這個程序中,您將在文本框中輸入一個數字(僅1-9),然後單擊Enter,而不必單擊按鈕將我在第二個標籤上顯示的文本框中編號的編號。我不斷收到兩個錯誤,第一拋出了一個如何在C#中的文本框中添加鍵盤快捷鍵(輸入)?

No overload for 'textBox1_TextChanged' matches delegate 'EventHandler'

當我添加KeyEventArgs(因爲EventArgs不包含Keycode)。第二個是標誌這裏:

this.label2.Click += new System.EventHandler(this.label2_Click);  

「CS1061‘Form1中’不包含關於‘label2_Click’和 沒有擴展方法的定義‘label2_Click’接受型 ‘Form1中’的第一個參數可以發現(是否缺少using指令或程序 集引用?)」

我的代碼:

using System; 
using System.Windows.Forms; 

namespace Tarea7 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      if (e.KeyCode == Keys.Enter) 
      { 
       label2.Text = textBox1.ToString(); 
      } 
      if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]")) 
      { 
       MessageBox.Show("Debes de escribir un numero de 1-9"); 
       textBox1.Text.Remove(textBox1.Text.Length - 1); 
      } 
     } 

     private void label2_TextChanged(object sender, EventArgs e) 
     { 

     } 
    } 
} 
+0

錯誤是自描述。 「TextChanged」事件不接受「KeyEventArgs」。此外,您的班級中沒有'label2_Click'方法。 –

+0

您不需要處理'TextChanged'事件。在你的窗體上放一個'Button',並處理按鈕的Click事件,並在按鈕點擊事件處理程序中執行你需要的操作。然後,將該按鈕設置爲表單的「AcceptButton」屬性的值就足夠了。這樣,當你輸入時,你的按鈕的代碼就會執行。 –

+0

感謝您的回覆,但我參加了一門課程,並且表示我應該使用標籤並且不使用按鈕。我嘗試將'TextChanged'更改爲'KeyPress'和'KeyDown',因爲它不支持'KeyEventArgs',但我不斷收到錯誤。 – Dotol

回答

0

textBox1_KeyDown事件的可視化設計器或文件Form1.designer.cs添加到您的textBox1.KeyDown事件:

this.textBox1.KeyDown += 
    new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown); 

然後添加下面的函數代碼。當用戶從1 - 9輸入一個數字並按Enter時,它將被複制到label2

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
    { 
     Text = DateTime.Now.ToString(); 
     switch (e.KeyCode) 
     { 
      case Keys.Enter: 
       if (textBox1.Text.Length == 1) 
       { 
        char tbChar = textBox1.Text[0]; 
        if (tbChar >= '1' && tbChar <= '9') 
        { 
         MessageBox.Show("Correct"); 
         label2.Text = tbChar.ToString(); 

         // Clear textbox 
         textBox1.Text = ""; 
         return; 
        } 
       } 
       MessageBox.Show("Your input is not a number from 1 - 9"); 
       break; 
     } 
    } 

而且,你並不需要這一行,將其刪除:

this.label2.Click += new System.EventHandler(this.label2_Click);