2016-03-04 134 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); 
相关问题