Limit the number of lines in a textbox

Asked

Viewed 987 times

2

It is possible to limit the number of lines in a textbox multiline using C# NET 3.5?

1 answer

4


There is no property that limits the number of lines in the TextBox, only the number of characters.

Nothing prevents you from implementing the event KeyDown, making a line count and avoid creating a new one when it reaches the limit.

Assuming you are using winforms:

int maxLines = 3;        
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (textBox1.Text.Split('\n').Length >= maxLines)
        {
            e.SuppressKeyPress = true;
        }
    }
}

Remembering that it would be necessary to set the property WordWrap for false in order to prevent the TextBox display a new line when the text reaches the end.

  • That’s if the person gives enter, if she types a huge text will not catch right?

  • I have just added an observation on this. If Wordwrap is not disabled I would not understand the meaning of limiting the number of lines and not the number of characters.

  • I’ve seen it now and I agree with you, I think it’s better to just limit the number of characters than lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.