Reputation: 391
I have text box where I want to send data (myButton) when I press Return.
private void txtBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Shift && e.KeyCode == Keys.Return)
{
// Shift + Return
}
else if (e.KeyCode == Keys.Return)
{
// Return
if (!String.IsNullOrWhiteSpace(txtBox.Text))
myButton.PerformClick();
}
}
This works fine if I have some text but when I don't have text, if I press Return it adds a new line and I don't want that. Any sugestion?
Upvotes: 1
Views: 79
Reputation: 942548
If you don't want lines to be added to the TextBox then you should set its Multiline property to False.
Generally, if you don't want the Enter key to be processed then you'll need to prevent the KeyPress event for it from firing. Which you do by setting the e.SuppressKeyPress property to true. Fix:
else if (e.KeyCode == Keys.Return)
{
// Return
if (!String.IsNullOrWhiteSpace(txtBox.Text))
myButton.PerformClick();
e.Handled = e.SuppressKeyPress = true;
}
Upvotes: 1