user3618909
user3618909

Reputation: 53

Do not allow Enter Key to make a new line in MultiLine TextBox C#

I set the property Multiline=true;.

I do not want to allow the Enter Key to make a new line.

How can I solve this issue?

Upvotes: 5

Views: 13503

Answers (2)

Aranxo
Aranxo

Reputation: 1183

Well, I am quite late to the party, but for others who read this I would mention that there is a property named TextBox.AcceptsReturn (Boolean).

Just set it in the properties window of the TextBox.

I had the same problem just the other way round: I had a multiline TextBox, but it didn't allow me to enter Returns.

Further information here:
https://learn.microsoft.com/dotnet/api/system.windows.forms.textbox.acceptsreturn?view=net-5.0

Upvotes: 3

dotNET
dotNET

Reputation: 35400

That could be as simple as listening to TextChanged event and then executing the following line inside it:

txtYourTextBox.Text = txtYourTextBox.Text.Replace(Environment.NewLine, "");

This solution involves some screen flicker though. A better way is to prevent it entirely by listening to KeyDown event:

private void txtYourTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
        e.SuppressKeyPress=true;
}

Upvotes: 7

Related Questions