TextBoxBase.MaxLength Property

Definition

Gets or sets the maximum number of characters the user can type or paste into the text box control.

C#
public virtual int MaxLength { get; set; }

Property Value

The number of characters that can be entered into the control. The default is 32767.

Exceptions

The value assigned to the property is less than 0.

Examples

The following code example uses the derived class, TextBox, to create a text box that is used to accept a password. This example uses the CharacterCasing property to change all characters typed to uppercase and the MaxLength property to restrict the password length to eight characters. This example also uses the TextAlign property to center the password in the TextBox control.

C#
public void CreateMyPasswordTextBox()
 {
    // Create an instance of the TextBox control.
    TextBox textBox1 = new TextBox();
    // Set the maximum length of text in the control to eight.
    textBox1.MaxLength = 8;
    // Assign the asterisk to be the password character.
    textBox1.PasswordChar = '*';
    // Change all text entered to be uppercase.
    textBox1.CharacterCasing = CharacterCasing.Upper;
    // Align the text in the center of the TextBox control.
    textBox1.TextAlign = HorizontalAlignment.Center;
 }

Remarks

You can use this property to restrict the length of text entered in the control for values such as postal codes and telephone numbers, or to restrict the length of text entered when the data is to be entered in a database. You can limit the text entered into the control to the maximum length of the corresponding field in the database.

Note

In code, you can set the value of the Text property to a value that has a length greater than the value specified by the MaxLength property. This property only affects text entered into the control at run time.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9