Limit number of lines in .net textbox

.net, windows, winforms

Solution

You need to check for

`txtbox.Lines.Length`

You need to handle this for 2 scenarios: 1. User is typing in the textbox 2. User has pasted text in the textbox

User typing in textbox

You need to handle the key press event of the text box to prevent user from entering more lines when max lines are exceeded.

private const int MAX_LINES = 10;

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (this.textBox1.Lines.Length >= MAX_LINES && e.KeyChar == '\r')
    {
        e.Handled = true;
    }
}

I have tested the above code. It works as desired.

User pastes some text in the textbox

To prevent the user from pasting more than the max lines, you can code the text changed event handler:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (this.textBox1.Lines.Length > MAX_LINES)
    {
        this.textBox1.Undo();
        this.textBox1.ClearUndo();
        MessageBox.Show("Only " + MAX_LINES + " lines are allowed.");
    }
}

Problem

I am using the winforms textbox with multiline option ON. I want to limit the number of lines that can be entered in it. User should not be able to enter lines more than that. How can I achieve that?

Original source