C# – How to limit number of characters to paste in the text box

cwinforms

I need to limit the number of characters to be pasted in a multiline textbox.

Let's say this is my string to be pasted in the textbox:

Good day Ladies and Gents!

I just want to know

If this is possible, please help.

The rule is maximum characters PER LINE is 10, Maximum ROWS is 2. Applying the rule, pasted text should only be like this:

Good day L

I just wan

Best Answer

There is not automatic what to do this. You'll need to handle the TextChanged event on the text box and manually parse the changed text to limit it to the format required.

private const int MaxCharsPerRow = 10;
private const int MaxLines = 2;

private void textBox1_TextChanged(object sender, EventArgs e) {
    string[] lines = textBox1.Lines;
    var newLines = new List<string>();
    for (int i = 0; i < lines.Length && i < MaxLines; i++) {
        newLines.Add(lines[i].Substring(0, Math.Min(lines[i].Length, MaxCharsPerRow)));
    }
    textBox1.Lines = newLines.ToArray();
}