MaskedTextBox
This accepts text input of a specific format. We often require phone numbers to have their area code and also the correct number of digits.
To solve this problem, we use the MaskedTextBox
control in Windows Forms. We can provide hints about what mistake caused the rejection.
Please add a MaskedTextBox
control to your Windows Forms program. Next, try changing the properties of the MaskedTextBox
by right-clicking on it and selecting properties.
MaskedTextBox
with the Social Security Number format specified.MaskedTextBox
control. We show the RejectionHint
and the Position of the error.using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { // Set the window title text // ... to the MaskInputRejectedEventArgs information. this.Text = "Error: " + e.RejectionHint.ToString() + "; position: " + e.Position.ToString(); } } }
The MaskedTextBox
can convert the input into a C# type. In this example, we set the format to the "Short
date" mask pattern.
TypeValidationCompleted
event handler by going to the event list in Visual Studio.ReturnValue
property from the TypeValidationEventArgs
. We need to cast this object.TypeValidationCompleted
event handler is triggered when the form is dismissed.using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e) { // This event is raised when the enclosing window is closed. // ... We show a MessageBox that details the DateTime. DateTime value = (DateTime)e.ReturnValue; MessageBox.Show("Validated: " + value.ToLongDateString()); } } }
AsciiOnly
The AsciiOnly
property enforces that every character entered not be an accented or Unicode-only character. This is useful when you require strict data input.
CutCopyMaskFormat
This property lets you adjust how the text will be copied. It specifies whether the separators are included in the copied text.
PasswordChar
and PromptChar
The MaskedTextBox
lets you change the character that appears when a password is entered. By default, the prompt character is an underscore "_".
MaskedTextBox
is a password box.ResetOnPrompt
and ResetOnSpace
These two properties are usability features. When you have a mask, there will be some prompt characters such as the "/" or "_" values.
MaskedTextBox
has one of those characters, this is considered valid input.The MaskedTextBox
control in Windows Forms enforces the range of input that is allowed into the text box. It is ideal for when you want to collect data like phone numbers.