Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit number of characters to paste in the text box?

Tags:

c#

winforms

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

like image 275
Jack Frost Avatar asked Jul 19 '13 03:07

Jack Frost


People also ask

How do I restrict the number of characters in a text box in HTML?

The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.

Is there a character limit in text boxes in Excel?

The text in the text box cuts off at 255 characters.

How can you set a character limit to a field?

To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element. To set the minimum character limit in input field, we use <input> minlength attribute.


1 Answers

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();
}
like image 115
shf301 Avatar answered Nov 02 '22 14:11

shf301