2010-11-25 58 views
0

好的,我希望用户能够在文本框输入过程中按下回车键来启动一个单击按钮。在C#中更新文本字段时按下Enter键时触发点击按钮#

我有以下代码:

 private void textBox1_KeyDown(object sender, KeyEventArgs e) 
    { 
      if (e.KeyValue == 13) 
      { 
       button3_Click(sender, e); 
      } 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 

     this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown); 
    } 
    private void button3_Click(object sender, EventArgs e) 
    { 
     if (textBox1.Text == "") 
     { 
      MessageBox.Show("Please enter a value.", "No name entered", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 
     else 
     { 
      if (listBox1.Items.Contains(textBox1.Text) == true) 
      { 
       MessageBox.Show("You have tried to enter a duplicate.", "No duplicates allowed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      } 
      else 
      { 
       listBox1.Items.Add(textBox1.Text); 
       textBox1.Text = ""; 
      } 
     } 


    } 

然而,当我按下输入值保存,然后在MessageBox出现“请输入一个值”的4倍。我怎样才能让这个代码在按下回车键后只发生一次button_click?

有没有更简单的方法来做到这一点?

谢谢!

回答

4
//Create a new button 
//Assuming you have a new button named "acceptButton" 
//Assuming your form name is "FormName" 
FormName.AcceptButton = acceptButton; 
//this button automatically is triggered at enter key is pressed 
acceptButton += new Click(acceptButton_Click); 

void acceptButton_Click(object sender, EventArgs e) { 
    button3_Click(sender, e); 
} 

//Make button3 the one to be activated when enter key is pressed 
FormName.AcceptButton = button3; 
//so that when enter key is pressed, button3 is automatically fired 
+0

谢谢。最终的代码在我的答案中提供。 – RHodgett 2010-11-29 15:24:12

-1

我不想让你感觉不好,但你想在textbox_textChanged方法中做什么?

你想要做的第一件事是删除它。它的作用是将button3_Click添加到KeyUp事件中。每次文本更改时都会再次添加,并且会多次调用button3_Click方法。

你得到的可能是“你试图输入重复”的消息。这是因为button3_Click方法被多次调用一次并且具有相同的值(第一次添加该值,并且在以下调用中它会尝试再次添加相同的值)。

在任何情况下,尝试添加信息到您的问题,这是非常不清楚(!)并需要一段时间才能理解。

+0

我从textbox_textchanged代码:http://www.neowin.net/forum/topic/422677-c%23-how-do-i-detect -enter-key-in-a-textbox/ – RHodgett 2010-11-25 17:28:27

0

吉安是对的,谢谢你。最后的代码是:

 private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyUp); 
    } 

    private void textBox1_KeyUp(object sender, KeyEventArgs e) 
    { 
     if (e.KeyValue == 13) 
     { 
      AcceptButton = button3; 
     } 
    } 
1

首先,我知道这是一个很老的帖子,其次,为什么你能不能简单地只使用文本框的KeyUp事件并调用按钮的Click事件:

private void textBox1_KeyUp(object sender, KeyEventArgs e) 
{ 
    if (e.KeyValue == 13) 
    { 
     this.Accept_Click(null, null); 
    } 
} 

除非我错过了很有可能的东西;-)

相关问题