Windows forms textbox mask

Masked Text Box. Mask Property

Definition

Gets or sets the input mask to use at run time.

Property Value

A String representing the current mask. The default value is the empty string which allows any input.

Exceptions

The string supplied to the Mask property is not a valid mask. Invalid masks include masks containing non-printable characters.

Remarks

Mask is the default property for the MaskedTextBox class.

Mask must be a string composed of one or more of the masking elements, as shown in the following table. The masking language used by MaskedTextBox is defined by its associated MaskedTextProvider. The standard provider specifies a masking language based upon the one used by the Masked Edit control in Visual Basic 6.0, and should be very familiar to users migrating from that platform.

Masking element Description
0 Digit, required. This element will accept any single digit between 0 and 9.
9 Digit or space, optional.
# Digit or space, optional. If this position is blank in the mask, it will be rendered as a space in the Text property. Plus (+) and minus (-) signs are allowed.
L Letter, required. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z] in regular expressions.
? Letter, optional. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z]? in regular expressions.
& Character, required. If the AsciiOnly property is set to true, this element behaves like the «L» element.
C Character, optional. Any non-control character. If the AsciiOnly property is set to true , this element behaves like the «?» element.
A Alphanumeric, required. If the AsciiOnly property is set to true , the only characters it will accept are the ASCII letters a-z and A-Z. This mask element behaves like the «a» element.
a Alphanumeric, optional. If the AsciiOnly property is set to true , the only characters it will accept are the ASCII letters a-z and A-Z. This mask element behaves like the «A» element.
. Decimal placeholder. The actual display character used will be the decimal symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
, Thousands placeholder. The actual display character used will be the thousands placeholder appropriate to the format provider, as determined by the control’s FormatProvider property.
: Time separator. The actual display character used will be the time symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
/ Date separator. The actual display character used will be the date symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
$ Currency symbol. The actual character displayed will be the currency symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
Shift up. Converts all characters that follow to uppercase.
| Disable a previous shift up or shift down.
\ Escape. Escapes a mask character, turning it into a literal. «\\» is the escape sequence for a backslash.
All other characters Literals. All non-mask elements will appear as themselves within MaskedTextBox. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.

If you change a mask when MaskedTextBox already contains user input filtered by a previous mask, MaskedTextBox will attempt to migrate that input into the new mask definition. If it fails, it will clear the existing input. Assigning a zero-length string as the mask will preserve any existing data in the control. When used with a zero-length mask, MaskedTextBox behaves like a single-line TextBox control.

The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to displaying those symbols as defined by the application’s culture. You can force them to display symbols for another culture by using the FormatProvider property.

Character insertion into the mask at run time is controlled by the InsertKeyMode property. Users can navigate through the mask by using the left and right arrow keys or the mouse cursor, and can skip optional positions in the mask by entering a space.

MaskedTextBox supports all Unicode characters except for surrogates and vertically combined characters.

Masked Text Box Конструкторы

Определение

Инициализирует новый экземпляр класса MaskedTextBox. Initializes a new instance of the MaskedTextBox class.

Перегрузки

Инициализирует новый экземпляр класса MaskedTextBox,используя значения по умолчанию. Initializes a new instance of the MaskedTextBox class using defaults.

Инициализирует новый экземпляр класса MaskedTextBox с помощью указанного поставщика нестандартного языка для маски. Initializes a new instance of the MaskedTextBox class using the specified custom mask language provider.

Инициализирует новый экземпляр класса MaskedTextBox, используя указанную маску ввода. Initializes a new instance of the MaskedTextBox class using the specified input mask.

MaskedTextBox()

Инициализирует новый экземпляр класса MaskedTextBox,используя значения по умолчанию. Initializes a new instance of the MaskedTextBox class using defaults.

Комментарии

Конструктор по умолчанию MaskedTextBox() задает MaskedTextProvider для свойства маску null, представленную строкой «<>«. The default MaskedTextBox() constructor sets the MaskedTextProvider property to a null mask, represented by the string «<>«. Маска null будет принимать любое сочетание символов в качестве входных данных. A null mask will accept any combination of characters as input.

См. также раздел

Применяется к

MaskedTextBox(MaskedTextProvider)

Инициализирует новый экземпляр класса MaskedTextBox с помощью указанного поставщика нестандартного языка для маски. Initializes a new instance of the MaskedTextBox class using the specified custom mask language provider.

Параметры

Поставщик нестандартного языка для маски, производный от класса MaskedTextProvider. A custom mask language provider, derived from the MaskedTextProvider class.

Исключения

maskedTextProvider имеет значение null . maskedTextProvider is null .

Комментарии

maskedTextProvider Параметр определяет язык маскирования, используемый MaskedTextBox . The maskedTextProvider parameter defines the masking language used by MaskedTextBox. Он отвечает за синтаксический анализ маски и определение того, соответствует ли введенные данные пользователю текущей позицией маски. It is responsible for parsing the mask and determining whether user input conforms to the current mask position. Можно создать новый класс из System.ComponentModel.MaskedTextProvider , чтобы определить собственный язык маскирования, и использовать MaskedTextBox(MaskedTextProvider) конструктор для замены стандартного System.ComponentModel.MaskedTextProvider . You can derive a new class from System.ComponentModel.MaskedTextProvider to define your own custom masking language, and use the MaskedTextBox(MaskedTextProvider) constructor to replace the standard System.ComponentModel.MaskedTextProvider.

Если вы хотите использовать язык маскировки по умолчанию и указать собственную маску ввода, использовать этот конструктор не нужно. If you want to use the default masking language and supply your own input mask, you do not need to use this constructor. Вместо этого можно либо использовать MaskedTextBox(String) конструктор, либо использовать конструктор без параметров, а затем задать Mask свойство. Instead, you can either use the MaskedTextBox(String) constructor, or use the parameterless constructor then set the Mask property.

Masked Text Box. Mask Свойство

Определение

Получает или задает маску ввода для использования во время выполнения. Gets or sets the input mask to use at run time.

Значение свойства

Строка String, представляющая текущую маску. A String representing the current mask. По умолчанию используется пустая строка, которая разрешает ввод любых символов. The default value is the empty string which allows any input.

Исключения

Свойству Mask передана строка, недопустимая в качестве маски. The string supplied to the Mask property is not a valid mask. К недопустимым маскам относятся те, которые содержат непечатаемые символы. Invalid masks include masks containing non-printable characters.

Комментарии

Mask свойство по умолчанию для MaskedTextBox класса. Mask is the default property for the MaskedTextBox class.

Mask должен быть строкой, состоящей из одного или нескольких элементов маскировки, как показано в следующей таблице. Mask must be a string composed of one or more of the masking elements, as shown in the following table. Язык маскирования, используемый, MaskedTextBox определяется связанным с ним MaskedTextProvider . The masking language used by MaskedTextBox is defined by its associated MaskedTextProvider. Стандартный поставщик определяет язык маскирования на основе того, который используется маскированным элементом управления «поле ввода» в Visual Basic 6,0 и должен быть очень знаком пользователям, переносящим эту платформу. The standard provider specifies a masking language based upon the one used by the Masked Edit control in Visual Basic 6.0, and should be very familiar to users migrating from that platform.

Маскирование элемента Masking element Описание Description
0 0 Цифра, обязательное. Digit, required. Этот элемент будет принимать любую цифру от 0 до 9. This element will accept any single digit between 0 and 9.
9 9 Цифра или пробел, необязательно. Digit or space, optional.
# Цифра или пробел, необязательно. Digit or space, optional. Если эта ячейка в маске пуста, она будет отображена в качестве пробела в Text свойстве. If this position is blank in the mask, it will be rendered as a space in the Text property. Разрешены знаки плюс (+) и минус (-). Plus (+) and minus (-) signs are allowed.
L L Буква, обязательная. Letter, required. Ограничивают ввод буквами ASCII a-z и A-Z. Restricts input to the ASCII letters a-z and A-Z. Этот элемент маски эквивалентен [a-zA-Z] в регулярных выражениях. This mask element is equivalent to [a-zA-Z] in regular expressions.
? ? Letter, необязательно. Letter, optional. Ограничивают ввод буквами ASCII a-z и A-Z. Restricts input to the ASCII letters a-z and A-Z. Этот элемент маски эквивалентен [a-zA-Z]? This mask element is equivalent to [a-zA-Z]? в регулярных выражениях. in regular expressions.
& Символ, обязательный. Character, required. Если AsciiOnly свойство имеет значение true, этот элемент ведет себя как элемент «L». If the AsciiOnly property is set to true, this element behaves like the «L» element.
C C Символ, необязательный. Character, optional. Любой символ, не являющийся управляющей. Any non-control character. Если AsciiOnly свойство имеет значение true , этот элемент ведет себя как элемент «?». If the AsciiOnly property is set to true , this element behaves like the «?» element.
Объект A Буквенно-цифровой, обязательный. Alphanumeric, required. Если AsciiOnly свойство имеет значение true , единственные символы, которые он будет принимать, — это буквы ASCII a – z и a – z. If the AsciiOnly property is set to true , the only characters it will accept are the ASCII letters a-z and A-Z. Этот элемент маски ведет себя как элемент «a». This mask element behaves like the «a» element.
а a Буквенно-цифровой, необязательный. Alphanumeric, optional. Если AsciiOnly свойство имеет значение true , единственные символы, которые он будет принимать, — это буквы ASCII a – z и a – z. If the AsciiOnly property is set to true , the only characters it will accept are the ASCII letters a-z and A-Z. Этот элемент маски ведет себя как элемент «A». This mask element behaves like the «A» element.
. . Заполнитель десятичных чисел. Decimal placeholder. Фактически используемый отображаемый символ будет являться десятичным символом, соответствующим поставщику формата, как определено FormatProvider свойством элемента управления. The actual display character used will be the decimal symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
, , Заполнитель тысяч. Thousands placeholder. Фактически используемый отображаемый символ будет заполнительом тысяч, соответствующим поставщику формата, как определено FormatProvider свойством элемента управления. The actual display character used will be the thousands placeholder appropriate to the format provider, as determined by the control’s FormatProvider property.
: : Разделитель времени. Time separator. Фактически используемым отображаемым символом будет символ времени, соответствующий поставщику формата, как определено FormatProvider свойством элемента управления. The actual display character used will be the time symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
/ Разделитель даты. Date separator. Фактический отображаемый символ будет использоваться в качестве символа даты, соответствующего поставщику формата, как определено FormatProvider свойством элемента управления. The actual display character used will be the date symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
$ Символ валюты. Currency symbol. Фактически отображаемый символ будет символом валюты, соответствующим поставщику формата, как определено свойством элемента управления FormatProvider . The actual character displayed will be the currency symbol appropriate to the format provider, as determined by the control’s FormatProvider property.
Сдвинуть вниз. Shift down. Преобразует все символы, указанные после, в нижний регистр. Converts all characters that follow to lowercase.
> Сдвинуть вверх. Shift up. Преобразует все символы, следующие за прописной буквой. Converts all characters that follow to uppercase.
| | Отключить предыдущую смену вверх или Сдвинуть вниз. Disable a previous shift up or shift down.
\ \ Выполняет. Escape. Обходит символ маски, преобразуя его в литерал. Escapes a mask character, turning it into a literal. » \ \ » — escape-последовательность для обратной косой черты. «\\» is the escape sequence for a backslash.
Все остальные символы All other characters Литералы. Literals. Все элементы, не являющиеся маской, будут отображаться в MaskedTextBox . All non-mask elements will appear as themselves within MaskedTextBox. Литералы всегда занимают статическую точку в маске во время выполнения и не могут быть перемещены или удалены пользователем. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.

Если изменить маску, если она MaskedTextBox уже содержит входные данные пользователя, отфильтрованные по предыдущей маске, MaskedTextBox попытается перенести эти входные данные в новое определение маски. If you change a mask when MaskedTextBox already contains user input filtered by a previous mask, MaskedTextBox will attempt to migrate that input into the new mask definition. В случае сбоя он очистит существующие входные данные. If it fails, it will clear the existing input. Назначение строки нулевой длины в качестве маски сохранит все существующие данные в элементе управления. Assigning a zero-length string as the mask will preserve any existing data in the control. При использовании с маской нулевой длины ведет себя MaskedTextBox как однострочный TextBox элемент управления. When used with a zero-length mask, MaskedTextBox behaves like a single-line TextBox control.

Символы Decimal (.), доли (,), Time (:), Date (/) и Currency ($) по умолчанию отображают эти символы в соответствии с языком и региональными параметрами приложения. The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to displaying those symbols as defined by the application’s culture. Можно принудительно отображать символы для другого языка и региональных параметров с помощью FormatProvider Свойства. You can force them to display symbols for another culture by using the FormatProvider property.

Вставка символа в маску во время выполнения управляется InsertKeyMode свойством. Character insertion into the mask at run time is controlled by the InsertKeyMode property. Пользователи могут перемещаться по маске с помощью клавиш со стрелками влево и вправо или курсора мыши, а также пропускать необязательные позиции в маске, вводя пробел. Users can navigate through the mask by using the left and right arrow keys or the mouse cursor, and can skip optional positions in the mask by entering a space.

MaskedTextBox поддерживает все символы Юникода, кроме суррогатов и вертикально Объединенных символов. MaskedTextBox supports all Unicode characters except for surrogates and vertically combined characters.

В следующей таблице показаны примеры масок. The following table shows example masks.

Читайте также:  Permission denied kali linux ��� ���������
Оцените статью