Reputation: 51
I want to allow the user to send his message when he press enter in the textbox. I went to search and im using the sample codes below.
Now the problem is when i press enter, the event is triggered more than once like about 4-5 times.
Someone else suggested to use keyup. I have tried keyup, keydown and keypress. All have the same problem. How do i prevent it from firing the event more than once?
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Thank you!
Upvotes: 2
Views: 5469
Reputation: 36698
Sara and Jon have already provided the correct answer to your specific question. But if you want to go further and get a better understanding of how and when to use any particular key handling event take a look at my article Exploring Secrets of .NET Keystroke Handling. I explain and diagram when and where each event is useful, plus provide a KeystrokeSandbox application that lets you actually watch what happens!
Upvotes: 0
Reputation: 437356
You are adding the KeyUp
event handler multiple times (inside the TextChanged
handler); therefore, when Enter is pressed, the handler executes multiple times.
What you want to do here is add the KeyUp
handler just once, inside your form's constructor, just after the InitializeComponent()
call:
public MyForm()
{
// other code possibly here
InitializeComponent();
// and now add the event handler:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Upvotes: 3
Reputation: 6999
Change your code to this
tbxAnswer.KeyUp -= tbxAnswer_KeyUp;
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
Upvotes: 1
Reputation: 1375
This is because every time you change the text, the tbxAnswer_TextChanged is called/ fired you assign an action to the keyup event; if the text is changed 4 times then you assigned the keyup event 4 times and it increases every time you change the text. try this out:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Upvotes: 3
Reputation: 26446
In your code snippet, whenever the text of the TextBox
changes, another eventhandler is added to the KeyUp
handler. You should only add event handlers once (for instance, just after creating the textbox).
Upvotes: 0