TextBoxBase.MaxLength 属性

定义

获取或设置用户可在文本框控件中键入或粘贴的最大字符数。

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

属性值

Int32

可以在文本框控件中输入的字符数。 默认值为 32767。

例外

分配给属性的值小于零。

示例

下面的代码示例使用派生类 TextBox创建用于接受密码的文本框。 此示例使用 CharacterCasing 该属性更改键入为大写的所有字符,并将 MaxLength 密码长度限制为 8 个字符。 此示例还使用 TextAlign 属性在控件中 TextBox 居中设置密码。

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;
 }

注解

可以使用此属性来限制在控件中输入的值(如邮政编码和电话号码)中的文本长度,或限制在数据库中输入数据时输入的文本长度。 可以将输入到控件中的文本限制为数据库中相应字段的最大长度。

备注

在代码中 Text ,可以将属性值设置为长度大于属性指定的 MaxLength 值的值。 此属性仅影响运行时输入到控件中的文本。

适用于

产品 版本
.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
Windows Desktop 3.0, 3.1, 5, 6, 7