好的,我希望用戶能夠在文本框輸入過程中按下回車鍵來啓動一個單擊按鈕。在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?
有沒有更簡單的方法來做到這一點?
謝謝!
謝謝。最終的代碼在我的答案中提供。 – RHodgett 2010-11-29 15:24:12