TextBoxBase.MaxLength 屬性

定義

取得或設定使用者能夠輸入或貼入文字方塊控制項中的最大字元數。

public:
 virtual property int MaxLength { int get(); void set(int value); };
public virtual int MaxLength { get; set; }
member this.MaxLength : int with get, set
Public Overridable Property MaxLength As Integer

屬性值

Int32

可以輸入控制項中的字元數。 預設值為 32767。

例外狀況

指派給屬性的值小於 0。

範例

下列程式碼範例會使用 衍生類別 TextBox ,建立用來接受密碼的文字方塊。 本範例會 CharacterCasing 使用 屬性,將輸入的所有字元變更為大寫,而 MaxLength 屬性則會將密碼長度限制為八個字元。 這個範例也會使用 TextAlign 屬性將 控制項中的密碼置中 TextBox

public:
   void CreateMyPasswordTextBox()
   {
      // Create an instance of the TextBox control.
      TextBox^ textBox1 = gcnew 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;
   }
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;
 }
Public Sub CreateMyPasswordTextBox()
    ' Create an instance of the TextBox control.
    Dim textBox1 As 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 = "*"c
    ' 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
End Sub

備註

您可以使用這個屬性來限制在控制項中輸入的文字長度,例如郵遞區號和電話號碼,或限制在資料庫中輸入資料時輸入的文字長度。 您可以將輸入控制項的文字限制為資料庫中對應欄位的最大長度。

注意

在程式碼中 Text ,您可以將 屬性的值設定為長度大於 屬性所 MaxLength 指定值的值。 此屬性只會影響執行時間輸入控制項中的文字。

適用於